Problem Description:
Given a character array consisting of numbers, convert it to the corresponding numeric value.
such as: {' 1 ', ' 2 ', ' 3 ', ' 4 '}---> 1234
4
34 = 3*10 + 4
234 = (2*10 + 3) *10 + 4 = 2*10*10 + 3*10 + 4
1234 = ((1*10 + 2) * 10 + 3) * 10 + 4 = 1*10*10*10 + 2*10*10+3*10+4
The Java code is as follows:
Public int atoi (char[] s) { int result = 0; for (int i = 0; i < s.length; i++) = result * + s[i]-' 0 '; return result; }
Solution Two, which is actually a recursion.
To "1234"---> 1234 first "123"--->123, then the ' 4 '--->4
In order to "123"--->123, first "a"--->12, then the ' 3 '--->3
....
Or you can understand this:
1234 = 123*10 + 4
123 = 12*10 + 3
12 = 1*10 + 2
....
The recursive implementation is as follows:
Public int strtoint (char[] c) { return recurse (c, c.length); } Private int recurse (charint len) {//len represents the length of char[] C if(len = = 1 ) return c[len-1]-' 0 '; Else return recurse (c, len-1) * + (c[len-1]-' 0 '); }
Character array converted to numbers