2

I'm totally new to Java and I'm implementing a simple function to convert string to integer on Leetcode.

public int myAtoi(String str) {
    if(str.length() == 0){
        return 0;
    }
    str = str.trim();
    int n = str.length();

    int signal = 0;
    if(n == 1 && str.equals("+") || str.equals("-")){
        return 0;
    }
    if(str.charAt(0) == '+'){
        signal = 1;
    }else if(str.charAt(0) == '-'){
        signal = -1;
    }

    int i = (signal != 0)? 1 : 0;
    if(signal == 0){
        signal = 1;//default
    }

    int res = 0;
    while(i < n){
        char c = str.charAt(i);
        if(!Character.isDigit(c)){
            return res * signal;
        }
        //res = res * 10 + c - '0';
        if(signal * res > Integer.MAX_VALUE){
            return Integer.MAX_VALUE;
        }
        if(signal * res < Integer.MIN_VALUE){
            return Integer.MIN_VALUE;
        }
        res = res * 10 + c - '0';
        ++i;
    }
    return res * signal;
}

I know java integer has the MAX_VALUE of 2147483647. When my input is 2147483648 the output should be 2147483647 but indeed it's -214748648. I really have no idea what's wrong in here. Can anybody help me to understand this?

2

2 Answers 2

2

Consider this example

public static void main(String args[]) {
    int i=2147483647;
    System.out.println("i="+i);
    int j=++i;
    System.out.println("Now i is="+i);
    System.out.println("j="+j);
}

What happens? output will be :

i = 2147483647
Now i is=-2147483648
j=-2147483648

The maximum value of integer is 2,147,483,647 and the minimum value is -2,147,483,648. Here in j (with post increment of i), we have crossed the maximum limit of an integer

This is exactly what is happening in your case too .

Because the integer overflows. When it overflows, the next value is Integer.MIN_VALUE

Why?

Integer values are represented in binary form, and there is binary addition in java. It uses a representation called two's complement, in which the first bit of the number represents its sign. Whenever you add 1 to the largest Integer(MAX INT), which has a bit sign of 0, then its bit sign becomes 1 and the number becomes negative.

So, don't put > MAX INT as input, else put a condition in your code to check it on input itself.

Sign up to request clarification or add additional context in comments.

Comments

2

The input is never +2147483648 since that value can't be represented as a Java int.

It will wrap around to the negative number you observe, so accounting for that result.

1 Comment

Yeah I know it's right. But actually the input is a string and I want to convert it to the int.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.