Float.toString() 和 Integer.toString() 如何工作?
我如何实现将 float 或 int 转换为字符串的算法? 我找到了一个链接 http:// /geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-0-2-years-about-algorithms-13
但我无法理解那里给出的算法
How can i implement an algorithm to convert float or int to string?
I found one link
http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-0-2-years-about-algorithms-13
but i cant understand the algorithm given there
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
数字 0-9 在大多数字符编码中都是连续的,因此调整它的整数值在这里会有所帮助:
the numbers 0-9 are sequential in most character encoding so twiddling with the integral value of it will help here:
这是如何将整数转换为字符串的示例,我希望您能够从中找出如何将浮点数转换为字符串。
当然,这是非常未优化的,但它让您了解最基本的格式化是如何完成的。
请注意,
"" + x
的技术实际上被重写为类似的内容,所以不要认为所写的内容 100% 完全是如何完成的,看看是在一个对事物有更大的看法。
Here's a sample of how to do the integer to string, from it I hope you'll be able to figure out how to do the float to string.
This is of course, very unoptimized, but it gives you a feel for how the most basic formatting is accomplished.
Note that the technique of
"" + x
is actually rewritten to be something likeSo don't think that what is written is 100% exactly HOW it is done, look at is as what must happen in a larger view of things.
总体思路是通过余数十来选取最低有效数字。然后将该数字除以 10 并重复...直到剩下零。
当然,它比这更复杂一点,特别是在
float
情况下。简单的:
The general idea is to pick off the least significant digit by taking the number remainder ten. Then divide the number by 10 and repeat ... until you are left with zero.
Of course, it is a bit more complicated than that, especially in the
float
case.Easy:
好吧,你可以自己阅读代码。
Well, you can read the code yourself.