《程序员代码面试指南》第五章 字符串问题 将整数字符串转成整数值

题目
将整数字符串转成整数值
java代码
package com.lizhouwei.chapter5;

/**
 * @Description: 将整数字符串转成整数值
 * @Author: lizhouwei
 * @CreateDate: 2018/4/23 22:14
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter5_5 {
    public int convert(String str) {
        char[] chars = str.toCharArray();
        if(!isValid(chars)){
            return 0;
        };
        boolean posi = chars[0] != '-' ? true : false;
        int minq = Integer.MIN_VALUE / 10;
        int minr = Integer.MIN_VALUE % 10;
        int res = 0;
        int cur = 0;
        for (int i = posi ? 0 : 1; i < chars.length; i++) {
            cur = '0' - chars[i];
            if (res < minq || (res == minq && cur < minr)) {
                return 0;
            }
            res = res * 10 + cur;
        }
        if (posi && res == Integer.MIN_VALUE) {
            return 0;
        }
        return posi ? -res : res;
    }

    public boolean isValid(char[] chars) {
        if (chars[0] != '-' && (chars[0] < '0' || chars[0] > '9')) {
            return false;
        }
        if (chars[0] == '-' && (chars.length == 1 || chars[0] == '0')) {
            return false;
        }
        if (chars[0] == '0' && (chars.length > 1)) {
            return false;
        }
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] < '0' || chars[i] > '9') {
                return false;
            }
        }
        return true;
    }

    //测试
    public static void main(String[] args) {
        Chapter5_5 chapter = new Chapter5_5();
        String str1 = "2147483647";
        String str2 = "2147483648";
        String str3 = "-2147483648";
        String str4 = "02147483648";
        System.out.println("2147483647转换为整数:" + chapter.convert(str1));
        System.out.println("2147483648转换为整数,会溢出:" + chapter.convert(str2));
        System.out.println("-2147483648转换为整数,不会溢出:" + chapter.convert(str3));
        System.out.println("02147483648转换为整数,不符合书写习惯:" + chapter.convert(str4));

    }
}
结果

1369004-20180423223248610-1116260331.png

转载于:https://www.cnblogs.com/lizhouwei/p/8922341.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值