剑指offer:将字符串转化为整数

题目叙述:

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

分析:

  • 字符串的第一个字符要单独考虑
  • 处理输入数据的上溢出和下溢出
  • java中的字符串不便于下标访问字符,考虑先将其转化为字符数组

代码:

public class Solution {
    public int StrToInt(String str) {
        if(str ==null || str.length()==0) return 0;
        //Java中的字符串不可以直接使用下标进行访问字符串中的字符,需要使用函数CharAt,因此为访问使用下标访问
        //考虑先将其转化为字符串数组
        char[] chars = str.toCharArray();
        int sig = 1; //用于标记正负号,默认是正号
        int res = 0;
        if((chars[0]<'0'||chars[0]>'9')&&chars[0]!='+'&&chars[0]!='-') return 0;
        if (chars[0] == '-') sig = -1;
        if(chars[0]>'0' && chars[0]<'9') res = chars[0]-'0';
        for(int i=1;i<str.length();i++){
            if(chars[i]<'0'||chars[i]>'9') return 0;    
            if(sig == -1){//处理下溢出
                if(res*10*sig<(Integer.MIN_VALUE+(chars[i]-'0'))) return 0;
            }
            else if( res*10>(Integer.MAX_VALUE-(chars[i]-'0')) ) return 0;//处理上溢出
            res = res*10+chars[i]-'0';
            
        } 
        return res*sig;
    }
}
发布了126 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zhpf225/article/details/103499052