美文网首页剑指offer最优解Java版
剑指offer最优解Java版-把字符串转换成整数

剑指offer最优解Java版-把字符串转换成整数

作者: 全菜工程师小辉 | 来源:发表于2019-07-08 13:26 被阅读3次

题目描述

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

解决方法

重点考察边界条件:

  1. 数据上下溢出
  2. 空字符串
  3. 只有正负号
  4. 有无正负号
  5. 错误字符串的输出
public class Solution
{
    public static int StrToInt(String str)
    {
        if (str.equals("") || str.length() == 0)
            return 0;
        char[] a = str.toCharArray();
        int negative = 0;
        if (a[0] == '-')
            negative = 1;
        long sum = 0;
        for (int i = negative; i < a.length; i++)
        {
            if (a[i] == '+')
                continue;
            if (a[i] < 48 || a[i] > 57)
                return 0;
            sum = sum * 10 + a[i] - 48;
            if((negative==0 && sum>Integer.MAX_VALUE) || (negative==1&&(sum*negative<Integer.MIN_VALUE))){
                return 0;
            }
        }
        return negative == 0 ? (int)sum : (int)sum * -1;
    }

    public static void main(String[] args) {
        System.out.println(StrToInt("-2147483648"));
    }
}

复杂度分析:

  • 时间复杂度:O(n)。
  • 空间复杂度:O(n)。
哎呀,如果我的名片丢了。微信搜索“全菜工程师小辉”,依然可以找到我

相关文章

网友评论

    本文标题:剑指offer最优解Java版-把字符串转换成整数

    本文链接:https://www.haomeiwen.com/subject/uryvcctx.html