I'm having string consisting of a sequence of digits (e.g. "1234"
). How to return the String
as an int
without using Java's library functions like Integer.parseInt
?
public class StringToInteger {
public static void main(String [] args){
int i = myStringToInteger("123");
System.out.println("String decoded to number " + i);
}
public int myStringToInteger(String str){
/* ... */
}
}
And what is wrong with this?
int i = Integer.parseInt(str);
EDIT :
If you really need to do the conversion by hand, try this:
public static int myStringToInteger(String str) {
int answer = 0, factor = 1;
for (int i = str.length()-1; i >= 0; i--) {
answer += (str.charAt(i) - '0') * factor;
factor *= 10;
}
return answer;
}
The above will work fine for positive integers - assuming that the string only contains numbers, otherwise the result is undefined. If the number is negative you'll have to do a little checking first, but I'll leave that as an exercise for the reader.