把字符串转换成整数

题目描述:将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

思路分析:要把字符串转换为整数主要考虑以下几种情况:

代码实现

public class Solution {
   public int StrToInt(String str) {
 
        if (str == null || str.length() == 0 || hasNonNumerical(str)) {
            // 如果字符串为空并且包含非数字字符
            return 0;
        }
 
        // 此时的字符串肯定是数字字符串
        // 因为返回值限定为int型,所以无需考虑大数问题
        char firstChar = str.charAt(0);
        // 先将除第一位的数字转换成整数
        int sumExcludeFirst = 0;
        int sum = 0;
        for (int i = 1; i < str.length(); i++) {
            // 拿出当前字符
            char c = str.charAt(i);
            // 将当前字符转换为整数
            int convert = c - '0';
 
            if (firstChar == '+' && sum <= Integer.MAX_VALUE) {
                sum += convert * Math.pow(10, str.length() - 1 - i);
            } 
 
            if (firstChar == '-' && sum >= Integer.MIN_VALUE) {
                sum -= convert * Math.pow(10, str.length() - 1 - i);
            }
 
            if (firstChar >= '0' && firstChar <= '9' && sum <= Integer.MAX_VALUE) {
                sum += convert * Math.pow(10, str.length() - 1 - i);
            }
 
        }
        
 
        int first = firstChar - '0';
        if (firstChar >= '0' && firstChar <= '9') {
            sum += first * Math.pow(10, str.length() - 1);
        }
        
        if (sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) {
            return 0;
        }
        return sum;
 
    }
 
    // 判断一个字符串除第一个字符外是否包含非数字字符,第一个字符可以是+或者是—
    private boolean hasNonNumerical(String str) {
 
        int length = str.length();
 
        // 取出第0位,若第0位如果是数字或者是+,—则继续遍历,否则直接返回false
        char c = str.charAt(0);
        if ((c >= '0' && c <= '9') || (c == '+') || (c == '-')) {
            // 有必要进行之后的遍历
            for (int i = 1; i < length; i++) {
                // 取出当前字符
                c = str.charAt(i);
                if (c < '0' || c > '9') {
                    // 证明包含非数字字符,直接跳出循环,返回false
                    return true;
                }
            }
 
        } else {
            // 首位就包含除正负号外的非数字字符
            return true;
        }
 
        return false;
    }
}

 

转载于:https://www.cnblogs.com/Dream-chasingGirl/p/10302809.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值