我最近在一次采访中被问到这个问题:
I was recently asked this question in an interview:
如何在不使用任何库的情况下将12345形式的字符串解析为其整数表示12345功能,而不管语言?
"How could you parse a string of the form '12345' into its integer representation 12345 without using any library functions, and regardless of language?"
我想到了两个答案,但面试官说有三分之一。以下是我的两个解决方案:
I thought of two answers, but the interviewer said there was a third. Here are my two solutions:
解决方案1:保留一个字典,其中包含'1'=> 1,'2'=> 2等。然后解析字符串一一次一个字符,查找字典中的字符,然后乘以位置值。求和结果。
Solution 1: Keep a dictionary which maps '1' => 1, '2' => 2, etc. Then parse the string one character at a time, look up the character in your dictionary, and multiply by place value. Sum the results.
解决方案2:一次解析一个字符,并从每个字符中减去0。这将给你'1' - '0'= 0x1,'2' - '0'= 0x2等。再次,乘以位值并对结果求和。
Solution 2: Parse the string one character at a time and subtract '0' from each character. This will give you '1' - '0' = 0x1, '2' - '0' = 0x2, etc. Again, multiply by place value and sum the results.
有人能想到第三种解决方案可能是什么吗?
Can anyone think of what a third solution might be?
谢谢。
推荐答案我希望这是面试官所追求的:
I expect this is what the interviewer was after:
number = "12345" value = 0 for digit in number: //Read most significant digit first value = value * 10 + valueOf(digit)此方法使用的操作远少于您概述的方法。
This method uses far less operations than the method you outlined.
更多推荐
如何在没有库函数的情况下将字符串解析为整数?
发布评论