如何在没有库函数的情况下将字符串解析为整数?

编程入门 行业动态 更新时间:2024-10-28 06:27:07
本文介绍了如何在没有库函数的情况下将字符串解析为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我最近在一次采访中被问到这个问题:

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.

更多推荐

如何在没有库函数的情况下将字符串解析为整数?

本文发布于:2023-10-25 22:34:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528310.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   字符串   情况下   库函数   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!