zoukankan      html  css  js  c++  java
  • 剑指offer-把字符串转换成整数

    题目描述

    将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

    输入描述:

    输入一个字符串,包括数字字母符号,可以为空

    输出描述:

    如果是合法的数值表达则返回该数字,否则返回0

    示例1

    输入

    复制

    +2147483647
        1a33

    输出

    复制

    2147483647
        0

    注意:在这里需要注意一下int类型的最大值和最小值。C++中,int占用4字节,32比特,数据范围为-2147483648~2147483647[-2^31~2^31-1]。
    class Solution {
    public:
        int StrToInt(string str) {
            int len = str.length();
            long sum=0;
            if(str[0]=='+' || str[0]=='-'){
                for(int i=1;i<len;i++){
                    if(str[i]>'9'||str[i]<'0')
                        break;
                    else{
                        int temp = str[i]-'0';
                        sum = sum*10+temp;
                    }
                }
                if(str[0]=='+'){
                    if(sum>2147483647){
                        return 0;
                    }else{
                        return sum;
                    }
                    
                }
                if(str[0]=='-'){
                    if(sum>2147483648){
                        return 0;
                    }
                    else{
                        return -sum;
                    }
                    
                }
                
            }else if(str[0]>='0' && str[0]<='9'){
                sum = str[0]-'0';
                for(int i=1;i<len;i++){
                    if(str[i]>'9'||str[i]<'0'){
                        return 0;
                    }
                    else{
                        int temp = str[i]-'0';
                        sum = sum*10+temp;
                    }
                }
                if(sum>2147483647){
                    return 0;
                }
                else{
                    return sum;
                }
               
            }
            else{
                return 0;
            }
        }
    };
  • 相关阅读:
    CentOS7安装注意
    ES插件安装
    CentOS7命令
    ES安装手册
    五 、redis-cluster java api
    四 、Redis 集群的搭建
    三 redis 的 java api(jedis)
    C#验证码 使用GDI绘制验证码
    云时代架构阅读笔记二——Java性能优化(二)
    【转载】Asp .Net Web Api路由路径问题
  • 原文地址:https://www.cnblogs.com/loyolh/p/12600672.html
Copyright © 2011-2022 走看看