如何在没有库函数的情况下将字符串解析为整数?
最近在一次采访中有人问我这个问题:
“如何在不使用任何库函数且不考虑语言的情况下将‘12345’形式的字符串解析为其整数表示形式 12345?”
我想到了两个答案,但面试官说还有第三个。 这是我的两个解决方案:
解决方案 1:保留映射 '1' => 的字典 1、'2' => 2 等。然后一次解析字符串一个字符,在字典中查找该字符,然后乘以位置值。 对结果求和。
解决方案 2:每次解析字符串一个字符,并从每个字符中减去“0”。 这将为您提供“1”-“0”= 0x1、“2”-“0”= 0x2 等。再次乘以位值并对结果求和。
谁能想到第三种解决方案可能是什么?
谢谢。
I was recently asked this question in an interview:
"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:
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.
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?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我想这就是面试官想要的:
这种方法使用的操作比您概述的方法少得多。
I expect this is what the interviewer was after:
This method uses far less operations than the method you outlined.
以相反的顺序解析字符串,使用解析个位数的两种方法之一,将累加器乘以 10,然后将该数字添加到累加器。
这样您就不必计算位值。 每次得到相同的结果时,将累加器乘以十。
Parse the string in oposite order, use one of the two methods for parsing the single digits, multiply the accumulator by 10 then add the digit to the accumulator.
This way you don't have to calculate the place value. By multiplying the accumulator by ten every time you get the same result.
Artelius 的答案非常简洁且与语言无关,但对于那些寻求更详细的答案和解释以及 C 和 Java 实现的人可以查看此页面:
http://www.programminginterview.com/content/strings
向下滚动(或搜索)到“练习问题:将 ASCII 编码字符串转换为整数”。
Artelius's answer is extremely concise and language independent, but for those looking for a more detailed answer with explanation as well as a C and Java implementation can check out this page:
http://www.programminginterview.com/content/strings
Scroll down (or search) to "Practice Question: Convert an ASCII encoded string into an integer."
// java 版本
//单元测试
}
// java version
//unit test
}
保留一个字典,将所有字符串映射到它们的整数对应项,直到一定限度? 可能没有多大意义,除非如果上限很小(例如两位或三位数),这可能会更快。
Keep a dictionary which maps all strings to their integer counterparts, up to some limit? Doesn't maybe make much sense, except that this probably is faster if the upper limit is small, e.g. two or three digits.
您始终可以尝试通过大量字符串表示形式的查找表进行二分搜索!
没有人谈论效率……:-)
You could always try a binary search through a massive look up table of string representations!
No-one said anything about efficiency... :-)
这是完整的程序,所有条件均为正、负,无需使用库
This is Complete program with all conditions positive, negative without using library