Compared with c++ ,java will return the suitable value when overflow


  • 0
    H

    class Solution {

    public int myAtoi(String str) {
        int flag = 1;
        int value = 0;
        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }
        if (str.charAt(0) == '-') {
            flag = -1;
            str = str.substring(1);
        } else if (str.charAt(0) == '+') {
            str = str.substring(1);
        }
        int i = 0;
        for (; i < str.length(); i++) {
            if (str.charAt(i) < '0' || str.charAt(i) > '9') {
                break;
            }
    
        }
        for (int z = 0; z < i; z++) {
            value += flag * Integer.parseInt(String.valueOf(str.charAt(z))) * Math.pow(10, i - z - 1);
    
        }
        return value;
    
    }
    

    }


Log in to reply
 

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