• 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;
        }
    }
  • 相关阅读:
    code review
    设计原则
    知识点介绍
    REST API
    第四章 模块化React和Redux应用
    第3章 从Flux到Redux
    第二章 设计高质量的React组件
    React和Jquery比较
    第一章 React新的前端思维方式
    封装一个获取module.exports内容的方法
  • 原文地址:https://www.cnblogs.com/resort-033/p/13567738.html
Copyright © 2020-2023  润新知