首页 > 其他 > 详细

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

时间:2020-08-26 21:59:57      阅读:86      评论:0      收藏:0      [点我收藏+]

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

   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;
    }
}

 

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

原文:https://www.cnblogs.com/resort-033/p/13567738.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!