簡體   English   中英

我自己的字符串到 Integer (atoi) function 不能正常工作

[英]my own String to Integer (atoi) function doesn't work correctly

我的代碼可以解釋前導空格和非數字字符。 它失敗了第四和第五種情況。 輸入:s = "words and 987" 和輸入:s = "-91283472332" 案例。 我不確定如何解釋這些情況。

class Solution {
    public int myAtoi(String s) {
        int length = s.length();
        boolean pos = true;
        int i = 0, num = 0;
        
        if(s.length() == 0) {
            return 0;
        }
        
        while(s.charAt(i) == ' ') {
            i++;
        }
        
        if(s.charAt(i) == '-') {
            pos = false;
            i++;
        }
        else if(s.charAt(i) == '+') {
            pos = true;
            i++;
        }
        
        while(i < length) {
            if(Character.isDigit(s.charAt(i))) {
                num = (num * 10) + Character.getNumericValue(s.charAt(i));
            } 
            i++;
        }
        
        if(!pos) {
            num *= -1;
        }
        
        if(num < Integer.MIN_VALUE) {
            num = Integer.MIN_VALUE;
        }
        else if(num > Integer.MAX_VALUE) {
            num = Integer.MAX_VALUE;
        }
        
        return num;
    }
}
public static int myAtoi(String str) {
    StringBuilder buf = new StringBuilder();

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);

        if (buf.length() == 0) {
            if (ch == '-' || ch == '+' || (ch >= '0' && ch <= '9'))
                buf.append(ch);
            else if (ch != ' ')
                return 0;
        } else if (ch < '0' || ch > '9')
            break;
        else
            buf.append(ch);
    }

    try {
        BigDecimal res = new BigDecimal(buf.toString());

        if (res.compareTo(BigDecimal.valueOf(Integer.MAX_VALUE)) > 0)
            return Integer.MAX_VALUE;
        if (res.compareTo(BigDecimal.valueOf(Integer.MIN_VALUE)) < 0)
            return Integer.MIN_VALUE;

        return res.intValue();
    } catch(Exception e) {
        return 0;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM