JAVA-------Easy Version To Understand!!!!!!!!!!


  • 46
    H
    	public static int myAtoi(String str) {
    	if (str == null || str.length() == 0)
    		return 0;//
    	str = str.trim();
    	char firstChar = str.charAt(0);
    	int sign = 1, start = 0, len = str.length();
    	long sum = 0;
    	if (firstChar == '+') {
    		sign = 1;
    		start++;
    	} else if (firstChar == '-') {
    		sign = -1;
    		start++;
    	}
    	for (int i = start; i < len; i++) {
    		if (!Character.isDigit(str.charAt(i)))
    			return (int) sum * sign;
    		sum = sum * 10 + str.charAt(i) - '0';
    		if (sign == 1 && sum > Integer.MAX_VALUE)
    			return Integer.MAX_VALUE;
    		if (sign == -1 && (-1) * sum < Integer.MIN_VALUE)
    			return Integer.MIN_VALUE;
    	}
    
    	return (int) sum * sign;
    }

  • 1
    W

    hey i have a small question, since sum is an int how can " sum > Integer.MAX_VALUE" or, Integer.MAX_VALUE is a signed value and sum is an unsigned integer?


  • 0
    H

    sum is defined as long, not int.please notice it!By the way,plz vote me for this problem,thanks.


  • 2
    M

    I am Chinese.Where are you from?


  • 0
    P

    i like solutions that are easy to understand. Thanks


  • 1
    R

    Can you explain "sum = sum * 10 + str.charAt(i) - '0';" this part in the code.


  • 0
    A

    Should we also not include " " as an edge case in:
    if (str == null || str.length() == 0 || str == " ")
    return 0;//


  • 0

    @ramunerella I am also interested in knowing how this line of code works. Did you find a solution yet?


  • 0

    I believe this is a lot simpler:

    int myAtoi(String str) {
      try {
        BigInteger value = new BigInteger(str.replaceFirst("^\\s*([+-]?\\d+).*?$", "$1"));
        return (value.signum() < 0
                ? value.max(BigInteger.valueOf(Integer.MIN_VALUE)).intValue()
                : value.min(BigInteger.valueOf(Integer.MAX_VALUE)).intValue();
      } catch (NumberFormatException e) {
          return 0;
      }
    }
    
    

    note, you'll have to import java.math.BigInteger


  • 0
    S

    @HelloWorld123456 this code is wrong, try input "-15\u0967". I've submitted new test cases to make this code not passing.


  • 0
    T

    @HelloWorld123456 If the test sample is" abc+1234-345", how to handle it


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.