Leetcode第八题——给定随意字符串转整数

首先,完成此题需要了解一些内容:

   Character.isDigit():取到字符串中为数字的字符。

   char-'0':因为根据码表,号码减去'0'则为对应数的int值。

题目正文:

  

  代码:

    

class Solution {
     public int myAtoi(String str){
        char[] chars = str.toCharArray();
        int n=chars.length;
        int idx=0;
        //判断开头是否为空字符
        while(idx<n&&chars[idx]==' '){
            idx++;
        }
        if(idx==n){
            return 0;

        }
        boolean negative=false;
        if(chars[idx]=='-'){
            negative=true;
            idx++;
        }else if (chars[idx]=='+'){
            negative=false;
            idx++;
        }else if(!Character.isDigit(chars[idx])){
            return 0;
        }
        int ans=0;
        //判断溢出
        while(idx<n&&Character.isDigit(chars[idx])){
            int digit=chars[idx]-'0';
            if(ans>(Integer.MAX_VALUE-digit)/10){
                return negative?Integer.MIN_VALUE:Integer.MAX_VALUE;
            }
            ans=ans*10+digit;
            idx++;
        }
        

        return negative?-ans:ans;
    }
}

 

posted @ 2020-08-26 20:53  huxiaojie  阅读(104)  评论(0编辑  收藏  举报