I know that one solution to do this is the following:
String tmp = "12345";
int result = 0;
for (int i =0; i < tmp.length(); i++){
char digit = (char)(tmp.charAt(i) - '0');
result += (digit * Math.pow(10, (tmp.length() - i - 1)));
}
System.out.println(result);
What I don't understand is why is:
char digit = (char)(tmp.charAt(i) - '0');
How can this convert into a digit?
char digit = (char)(tmp.charAt(i) - '0');
In the ascii table, characters from '0'
to '9'
are contiguous. So, if you know that tmp.charAt(i)
will return a character between 0
and 9
, then subracting 0
will return the offset from zero, that is, the digit that that character represents.
Using Math.pow is very expensive, you would be better off using Integer.parseInt.
You don't have to use Math.pow. If your numbers are always positive you can do
int result = 0;
for (int i = 0; i < tmp.length(); i++)
result = result * 10 + tmp.charAt(i) - '0';
char
is an integer type that maps our letters to numbers a computer can understand (see an ascii chart). A string is just an array of characters. Since the digits are contiguous in ascii representation, '1' - '0' = 49 - 48 = 1
, '2' - '0' = 50 - 48 = 2
, etc.
Try this:
int number = Integer.parseInt("12345")
// or
Integer number = Integer.valueOf("12345")
atoi
could be a bit mistery for developers. Java prefers more readable names
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With