zoukankan      html  css  js  c++  java
  • 【LeedCode】String to integer(atoi)

    Implement atoi to convert a string to an integer.

    Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

    Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

    列举需要注意的集中情况

    1、去空格 trim()

    2、首字母为“+”或者“-”,则要记录下来。设一个flag变量,用于存储符号位

    3、数字前出现了非数字字符,则返回0

    4、在数字中出现了非数字字符,则返回前面的一些数字字符组成的数,后面的直接舍弃

    5、存在数字越界的情况,所以要对最后得到的数字进行判断

    public static int atoi(String str){
            if(str == null || str.length() == 0)
            {
                return 0;
            }
            str = str.trim();
            int flag = 1;
            int start = 0;
            long res = 0;
            if(str.charAt(0)=='+'){
                flag = 1;
                start++;
            }else if(str.charAt(0)=='-'){
                flag = -1;
                start++;
            }
            for(int i = start;i<str.length();i++){
                if(Character.isDigit(str.charAt(i))){
                    return (int)res*flag;
                }
                res = res*10 + str.charAt(i)-'0';        
            }
            if (flag == 1 && res > Integer.MAX_VALUE)
                return Integer.MAX_VALUE;
            if (flag == -1 && (-1) * res < Integer.MIN_VALUE)
                return Integer.MIN_VALUE;
            
            return (int)(flag * res);
            
        }
  • 相关阅读:
    学习笔记:模拟退火
    我的 2020
    高一上文化课期末复习
    IOI 2020-2021 集训队作业
    学习笔记:插头DP
    NOIP2020 游记
    刷题记录
    学习笔记:四边形不等式优化 DP
    操作集合时 报错 java.lang.UnsupportedOperationException
    【编码】接收前端参数时,偶数汉字正常,奇数汉字乱码
  • 原文地址:https://www.cnblogs.com/sMKing/p/6562004.html
Copyright © 2011-2022 走看看