《剑指 Offer》——49、把字符串转换为整数

1. 本题知识点

字符串

2. 题目描述

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

3. 解题思路

首先,字符串是否合法,我们可以使用正则表达式去判断。

([+-]?)(\\d+)

接下来,我们需要考虑,这个整数字符串有可能不在整数范围 [Integer.MIN_VALUE, Integer.MAX_VALUE] 内,所以我们需要分类讨论:

  1. 首先我们要先判断这个整数的正负

  2. 如果正数大于 Integer.MAX_VALUE 就返回 Integer.MAX_VALUE

  3. 如果负数小于 Integer.MIN_VALUE 就返回 Integer.MIN_VALUE

  4. 如果在范围内,直接调用下面的方法得到返回值,负数将返回值加负号就行

    public static int NumToInt(String str) {
        int num = 0;
        for (int i = 0; i < str.length(); i++) {
            num = num * 10 + (str.charAt(i) - '0');
        }
        return num;
    }
    

注意:我们在判断整数字符串是否在整数范围内的时候,只能使用字符串进行比较,所以把 Integer.MAX_VALUE 和 Integer.MIN_VALUE 也要转换为字符串。

4.代码

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Solution {
    // Int 最大值字符串
    private static final String MAX_VALUE = Integer.valueOf(Integer.MAX_VALUE).toString();
    // Int 最小值的绝对值字符串
    private static final String MIN_VALUE = Integer.valueOf(Integer.MIN_VALUE).toString().substring(1);

    public int StrToInt(String str) {
        Pattern pattern = Pattern.compile("([+-]?)(\\d+)");
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            String sign = matcher.group(1);
            String num = matcher.group(2);
            // 负数
            if ("-".equals(sign)) {
                if (num.length() > MIN_VALUE.length()) {
                    return Integer.MIN_VALUE;
                } else if (num.length() == MIN_VALUE.length() && num.compareTo(MIN_VALUE) > 0) {
                    return Integer.MIN_VALUE;
                } else {
                    return -(NumToInt(num));
                }
            }
            // 正数
            else {
                if (num.length() > MAX_VALUE.length()) {
                    return Integer.MAX_VALUE;
                } else if (num.length() == MAX_VALUE.length() && num.compareTo(MAX_VALUE) > 0) {
                    return Integer.MAX_VALUE;
                } else {
                    return NumToInt(num);
                }
            }
        } else {
            return 0;
        }
    }

    public static int NumToInt(String str) {
        int num = 0;
        for (int i = 0; i < str.length(); i++) {
            num = num * 10 + (str.charAt(i) - '0');
        }
        return num;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bm1998

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值