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
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.
the numbers 0-9 are sequential in most character encoding so twiddling with the integral value of it will help here:
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.