Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atoi in java using charAt

Tags:

java

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?

like image 761
xonegirlz Avatar asked Nov 07 '11 16:11

xonegirlz


4 Answers

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.

like image 71
Tom Avatar answered Sep 19 '22 12:09

Tom


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';
like image 33
Peter Lawrey Avatar answered Sep 17 '22 12:09

Peter Lawrey


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.

like image 45
Kevin Avatar answered Sep 16 '22 12:09

Kevin


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

like image 31
lukastymo Avatar answered Sep 17 '22 12:09

lukastymo