Leet Code OJ 8. String to Integer (atoi) 字符串转数字

Leet Code OJ 8. String to Integer (atoi) [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.

翻译:
实现一个atoi函数来把字符串转换为整型变量。

分析:
这道题的AC率只有13.4%,主要是因为对特殊情况的处理上。具体有这么几种情况需要考虑:
1. 前面的空格
2. 除去前面的空格后,可以以“+、-、0”开头,需要做对应的处理
3. 除了起始处可以出现前2种情况提到的非数字字符,其他地方一旦出现,则忽略该字符以及其后的字符
4. 考虑边界,即是否超出Integer.MAX_VALUE,Integer.MIN_VALUE。下面的方案采用long作为临时存储,方便做边界的判断。但是还要考虑是否会超出long的最大值,对此,我加了一个哨兵来判断.

java 版ac代码


class Solution {
    public int myAtoi(String str) {
        int flag = 1;
        int index=0;
        Long ans = 0L;
        Long ans1=0L;
       char [] str1=str.toCharArray();
  
       for(char i: str1){
           ans1 = ans;
      
        if(index==0){

                if(i==' ')
                continue;
                else if(i=='+'){
                    index=1;
                    continue;
                }else if(i=='-'){
                    flag=-1;
                    index=1;
                    continue;
                }else  if(i>='0'&&i<='9')
                {
                    index=1;
                }
               else {
                   break;
                      
               }
        }
        if(index==1){
            if (i >= '0' && i <= '9') {
                ans = ans * 10 + (i - '0');
                
            } else
                break;
        }
        if(ans<ans1)
        {
            if(flag>0)
            return Integer.MAX_VALUE;
            else return Integer.MIN_VALUE;
        }
        
       }
       ans = ans * flag;
       if(ans> Integer.MAX_VALUE)
       {
           System.out.print(ans);
           return Integer.MAX_VALUE;
       }
       
       else if( -ans >Integer.MAX_VALUE){
           return Integer.MIN_VALUE;
       }

        return ans.intValue();
    }
   
}

 其实这道题还有其他解法,比如判断数字长度来进行溢出判断.甚至我还看到有大佬直接用正则表达式解的.待日后再研究.

仅供记录日常刷题,大佬勿喷,欢迎各路大神指点.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值