LeetCode:String to Integer (atoi)没你想的那么简单

题目:

  Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

spoilers alert… click to show requirements for atoi.

Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.  

解题思路:

  要是直接用java里面的Integer.toString()函数,那也太简单啦,考虑的点比较多,一点没考虑到,就Ac不了。不用多说,上代码。

代码如下:

package com.java.day01;
/**
 * Date:     2017年4月10日 上午8:36:31
 * @author   maskwang 
 * @since    JDK 1.6
 */
public class Solution {
    public static int myAtoi(String str) {
        if (str == null || str.equals(""))
            return 0;   //如果字符串为空或者空串,直接返回0;
        int i = 0, len = str.length();
        char c = '+';  //这个变量用来记住符号为,初始化为整数
        StringBuilder sb = new StringBuilder();

        while (i < len && str.charAt(i) == 32)
            i++;  //跳过刚开始连续的空格
        while (i < len && str.charAt(i) == '0')
            i++;//跳过刚开始连续的0
        if (i == len) {
            return 0;//如果是整个字符串都为空串,或者只有’0',则直接返回0
        }
        if (str.charAt(i) == '+' || str.charAt(i) == '-') {
            if (str.charAt(i) == '-')
                c = '-';
            i++;//跳过符号位
        }

        if (i == len || (!(str.charAt(i) >= '0' && str.charAt(i) <= '9')))
            return 0;//如果不是0~9就返回0
        sb.append(c);//把符号位加入进去
        for (; i < len; i++) {
            if (str.charAt(i) >= '0' && str.charAt(i) <= '9')
                sb.append(str.charAt(i));//加入正常字符
            else
                break;
        }

        String str1 = sb.toString();
        if (str1.charAt(0) == '+' && str1.length() > 10) {//关键点:如果为正数,只要当位数超过10
                                                 //位才进入大数处理
            if (str1.length() > 11 || str1.compareTo("+2147483647") > 0)
                return 2147483647;//如果位数超过11位,直接超出范围,
                                //返回就行。或者比规定最大int的正数大数,返回过去
                                //就行 
        }
        if (str1.charAt(0) == '-' && str1.length() > 10) {
            if (str1.length() > 11 || str1.compareTo("-2147483648") > 0) {
                return -2147483648;//注意是字符串比较,正负数没有关系,此处若大于
                                   //0,说明就是小于
                                   //最小int值
            }
        }
        int a = Integer.valueOf(str1);//正常的数,转化过去就行
        return a;

    }
    public static void main(String[] args) {
         int b=myAtoi("-11919730356");
         System.out.println(b);
    }

}

Note:

  大数判断非常关键,注意是字符串比较,不是数的比较。所以比最小的负数小,那么字符串比较就是比最小的负数的字符串大。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值