LeetCode—8. String to Integer (atoi)

8. String to Integer (atoi)

  My Submissions
Total Accepted: 106331  Total Submissions: 783579  Difficulty: Easy

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.

Subscribe to see which companies asked this question




String to Integer (atoi)思路:注意题目要求,有以下几点

1.大于Integer.MAX_VALUE的返回Integer.MAX_VALUE

2.小于Integer.MIN_VALUE的返回Integer.MIN_VALUE

3.符号出现2次返回0

4.出现过数字后再出现非数字的如空格或者英文直接返回前面读取到的数字

GitHub地址https://github.com/corpsepiges/leetcode

点此进入


public class Solution {
    public int myAtoi(String str) {
        char[] cs=str.toCharArray();
        long ans=0;
        int sign=1;
        boolean signFlag=true;
        int i=0;
        boolean zeroFlag=true;
        while (i < cs.length) {
            if (zeroFlag) {
                while (cs[i]==' ') {
                    i++;
                }
                zeroFlag=false;
            }
            if (!zeroFlag&&cs[i]==' ') {
                break;
            }
            if (cs[i]=='-'||cs[i]=='+') {
                if (signFlag) {
                    sign=44-cs[i];
                    signFlag=false;
                }else{
                    return 0;
                }
            }else if(cs[i]>='0'&&cs[i]<='9'){
                ans=10*ans+cs[i]-48;
                if (sign==1&&ans>=Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                }
                if (sign==-1&&ans-1>=Integer.MAX_VALUE) {
                    return Integer.MIN_VALUE;
                }
            }else{
                break;
            }
            i++;
        }
        return (int) (ans*sign);
    }
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值