Manually converting a string to an integer in Java

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, 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.


If the standard libraries are disallowed, there are many approaches to solving this problem. One way to think about this is as a recursive function:

  1. If n is less than 10, just convert it to the one-character string holding its digit. For example, 3 becomes "3".
  2. If n is greater than 10, then use division and modulus to get the last digit of n and the number formed by excluding the last digit. Recursively get a string for the first digits, then append the appropriate character for the last digit. For example, if n is 137, you'd recursively compute "13" and tack on "7" to get "137".

You will need logic to special-case 0 and negative numbers, but otherwise this can be done fairly simply.

Since I suspect that this may be homework (and know for a fact that at some schools it is), I'll leave the actual conversion as an exercise to the reader. :-)

Hope this helps!


Use long instead of int in this case. You need to check for overflows.

public static int StringtoNumber(String s) throws Exception{
    if (s == null || s.length() == 0)
        return 0;
    while(s.charAt(0) == ' '){
        s = s.substring(1);
    }
    boolean isNegative = s.charAt(0) == '-';
    if (s.charAt(0) == '-' || (s.charAt(0) == '+')){
        s = s.substring(1);
    }

    long result = 0l;
    for (int i = 0; i < s.length(); i++){
        int value = s.charAt(i) - '0';
        if (value >= 0 && value <= 9){
            if (!isNegative && 10 * result + value > Integer.MAX_VALUE ){
                throw new Exception();
            }else if (isNegative && -1 * 10 * result - value < Integer.MIN_VALUE){
                throw new Exception();
            }
            result = 10 * result + value;
        }else if (s.charAt(i) != ' '){
            return (int)result;
        }
    }
    return isNegative ? -1 * (int)result : (int)result;
}