• [LeetCode]-algorithms-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.

    需求:字符串转成数字,需要识别正负号

    ""
    =>0
    -1
    =>-1
    +-1
    =>0
    1234567890123456789012345678901234567890
    =>0
    "2147483648"
    =>2147483647

    public int myAtoi(String str) {
            str = str.trim();
            if(null==str || "".equals(str))
                return 0;
            char flag = '+';
            int i = 0;
            if(str.charAt(0)=='+'){
                flag = '+';
                i++;
            }else if(str.charAt(0)=='-'){
                flag = '-';
                i++;
            }
            double result = 0.0;
            if(str.length()>12)
                return 0;
            while(str.length()>i && str.charAt(i)>='0' && str.charAt(i)<='9'){
                result = result * 10 + (str.charAt(i)-'0');
                i++;
            }
            if(flag=='-')
                result = -result;
            if(result>Integer.MAX_VALUE)
                result = Integer.MAX_VALUE;
            if(result<Integer.MIN_VALUE)
                result = Integer.MIN_VALUE;
            return (int)result;
        }
  • 相关阅读:
    python 文件路径拼接、判断、创建、输出
    热力图制作
    矩阵文件添加列标签
    cmd运行 ‘.py’ 文件
    hdu 2017 字符串统计
    hdu 2016 数据的交换输出
    hdu 2014 青年歌手大奖赛_评委会打分
    hdu 2013 蟠桃记
    hdu 2012 素数判定
    hdu 2011 多项式求和
  • 原文地址:https://www.cnblogs.com/lianliang/p/5328401.html
Copyright © 2020-2023  润新知