This took me a while to figure out and i must say, it's genius :). First what you have to do is: seperate the digits. This is where being good with numbers really helps.
(i'm not going to write code, instead I'll give you a mathematical view point)
if you divide a number by 10, the decimal moves one point to the left:
1077 / 10 = 107.7
In order to get the decimal point i used a float, however that caused problems because float are never exact. So, i made two temporary int variables and did this:
1. temp = 1077 <- this is the integer being sent to the function
temp / 10 = 107 <- integers truncate decimal points
temp * 10 = 1070
2. temp2 = 1077 - temp
= 7
Hooray, i got the first digit separated. Now, just do char = temp2 + 48; and your first digit is successfully converted. Repeat this process for x amount of times and your string contains a 4 digit number. BUT WAIT, how do i determine x? dividing by 10 again.
make a while loop where you divide temp by 10 while temp > 0 and do an i++ to get how many digits are in the number. you can now use i for a for loop.
There you have it, a putint function that converts an integer into a string without using extra libraries (there is no atoi() or sprintf()).
o u sooooooo smart! :P
ReplyDelete