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);
            
        }
  • 相关阅读:
    hadoop SecondNamenode 详解
    LaTeX的图片插入及排版[转]
    Secondary Namenode
    分布式文件系统元数据服务模型【转】
    Linux查看物理CPU个数、核数、逻辑CPU个数
    TCP的滑动窗口机制【转】
    sysctl.conf
    Iperf[转]
    CVE-2017-11882漏洞利用
    2017EIS CTFwriteup
  • 原文地址:https://www.cnblogs.com/sMKing/p/6562004.html
Copyright © 2011-2022 走看看