剑指offer-67 字符串转整数

剑指offer-67 字符串转整数

题目:
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

思路:
分成两个部分,符号和数字
但需要注意的是:

  1. null
  2. 空字符串""
  3. 只有+-
  4. 有+-
  5. 非法字符

自己解答:

public class Solution {
    public int StrToInt(String str) {
        if(str == null || str.length() == 0) return 0;
        char[] ch = str.toCharArray();
        int res = Int(ch);
        return res;
    }
    private int unsignInt(char[] ch, int start){
        int res = 0;
        for(int i = start; i < ch.length; i++){
            if(ch[i] >= '0' && ch[i] <= '9'){
                res *= 10;
                res += (ch[i] - '0');
            }
            else{
                res = 0;
                break;
            }
        }
        return res;
    }
    private int Int(char[] ch){
        boolean isNegtive = false;
        int start = 0;
        if(ch[0] == '+'){
            start++;
        }else if(ch[0] == '-'){
            start++;
            isNegtive = true;
        }
        int res = unsignInt(ch, start);
        if(isNegtive)
            return -res;
        else
            return res;
    }
}

犯的错误:
这个代码没有考虑只有正负号(在无符号函数里面虽然会直接返回0,但本身我自己没有考虑得到),没有考虑上下溢出

注意:

优化:

public class Solution {
    public int StrToInt(String str) {
        if(str == null || str.length() == 0) return 0;
        char[] ch = str.toCharArray();
        int res = Int(ch);
        return res;
    }
    
    private int Int(char[] ch){
        int isNegtive = 1;
        int start = 0;
        if(ch[0] == '+'){
            start++;
        }else if(ch[0] == '-'){
            start++;
            isNegtive = -1;
        }
        long res = 0;
        for(int i = start; i < ch.length; i++){
            if(ch[i] >= '0' && ch[i] <= '9'){
                res *= 10;
                res += isNegtive * (ch[i] - '0');
                if(res > 0x7fff_ffff || res < 0x8000_0000){
                    res = 0;
                    break;
                }
            }
            else{
                res = 0;
                break;
            }
        }
        
        return (int)res;
    }
}

猜你喜欢

转载自www.cnblogs.com/muche-moqi/p/12393040.html
今日推荐