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?

Alejandro Alcalde
  • 5,990
  • 6
  • 39
  • 79
  • This happens when you overflow the integer capacity: https://en.wikipedia.org/wiki/Integer_overflow – Alejandro Alcalde Mar 08 '17 at 18:03
  • 2
    Possible duplicate of [why Integer.MAX\_VALUE + 1 == Integer.MIN\_VALUE?](http://stackoverflow.com/questions/9397475/why-integer-max-value-1-integer-min-value) – zanussi Mar 08 '17 at 18:03

2 Answers2

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
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.

minigeek
  • 2,766
  • 1
  • 25
  • 35