Solution by prehant


  • 0
    P

    class Solution {
    public int myAtoi(String str) {
    if (str.length() == 0)
    return 0;
    long number = 0;
    str = str.trim();
    Boolean has_sign = false;
    int i = 0;
    if (str.length() > 0 && (str.charAt(0) == '-' || str.charAt(0) == '+')) {
    has_sign = true;
    i = 1;
    }
    while(i < str.length() && Character.isDigit(str.charAt(i))) {
    number = number * 10 + Character.getNumericValue(str.charAt(i));
    i++;
    if(i == 12) {
    break;
    }
    }
    if(has_sign && str.charAt(0) == '-') {
    long neg = -1;
    number = neg * number;
    if (number < Integer.MIN_VALUE)
    return Integer.MIN_VALUE;
    else
    return Math.toIntExact(number);
    }
    else {
    if (number > Integer.MAX_VALUE)
    return Integer.MAX_VALUE;
    else
    return Math.toIntExact(number);
    }
    }
    }

    • list item

Log in to reply
 

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