剑指offer---49.把字符串转换成整数

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44406146/article/details/102754171

题目描述

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

输入描述:

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

输出描述:

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

示例1 输入

+2147483647
1a33

输出

2147483647
0

解法一:学习前面某题一老哥的骚操作

public class Solution {
    public int StrToInt(String str) {
        if(str==null||str.length()==0) return 0;
        try{
            int result = Integer.valueOf(str);
            return result;
        }catch(Exception e){
            return 0;
        }
    }
}

解法二:自己写的遍历转换

思路: 感觉有点low

public class Solution {
    public int StrToInt(String str) {
        if(str==null||str.length()==0) return 0;
        char c = str.charAt(0);
        long result;
        boolean flag = true;
        if(c>='0'&&c<='9') result = c-'0';
        else if(c=='+') result = 0;
        else if(c=='-'){
            flag = false;
            result = 0;
        }else return 0;
        if(str.length()>11) return 0;
        for(int i=1;i<str.length();i++){
            c = str.charAt(i);
             if(c>='0'&&c<='9'){
                 result = result*10+(c-'0');
             }else{
                 return 0;
             } 
        }
        if(flag==true&&result<=(long)Integer.MAX_VALUE){
            return (int)result;
        }
        if(flag==false&&(-result)>=(long)Integer.MIN_VALUE){
            return (int)-result;
        }
        return 0;
    }
}

解法三:优雅一下自己的代码

public class Solution {
    public int StrToInt(String str) {
        if(str==null||str.length()==0) return 0;
        char c = str.charAt(0);
        long result = 0;
        long flag = 1;
        if(c=='-') flag=-1;
        if(str.length()>11) return 0;
        for(int i=((c=='+'||c=='-')?1:0);i<str.length();i++){
            c = str.charAt(i);
             if(c>='0'&&c<='9'){
                 result = (result<<1)+(result<<3)+(c-'0');
             }else{
                 return 0;
             } 
        }
        result = flag*result;
        if(flag==1&&result>(long)Integer.MAX_VALUE) return 0;
        if(flag==-1&&result<(long)Integer.MIN_VALUE) return 0;
        return (int)result;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44406146/article/details/102754171