iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 14
0
自我挑戰組

有志者,事竟成。系列 第 14

Day14 LeetCode #8 String to Integer (atoi)

  • 分享至 

  • twitterImage
  •  

題目描述

將字串轉為數字。
符合以下幾種規則:
1.字串前方允許空白
2.字串後方若有字串,但前方為數字時,後方忽略不記。
3.到達非空白位置後若第一個字元非"+""-"數字則回傳0
4.若超過32bit,則依照正負輸出INT_MININT_MAX

思路

按照各種可能,避免發生即可。

程式碼

class Solution {
public:
    int myAtoi(string str) {
        bool flag = true;//true is positive
        bool enter=false;
        int ans=0;
        for(int i=0;i<str.length();i++)
        {
            if(enter&&str[i]<48||str[i]>57)
                break;
            if(str[i]=='-')
            {
                flag=false;
                if(str[i+1]<48||str[i+1]>57)
                    return 0;
            }
            else if(str[i]=='+')
            {
                flag=true;
                if(str[i+1]<48||str[i+1]>57)
                    return 0;
            }
            else if(str[i]==' ')
                continue;
            else if(str[i]<48||str[i]>57)
                return ans;
            else
            {
                enter=true;
                if(ans>214748364&&flag||(ans==214748364&&str[i]>'6'&&flag))
                    return 2147483647;
                else if(ans>214748364&&!flag||(ans==214748364&&str[i]>'7'&&!flag))
                    return -2147483648;
                else
                    ans=ans*10+(str[i]-48);
            }      
        }
        if(!flag)
            ans=-ans;
        return ans;
    }
};

心路歷程

大概就是不停測試的過程吧,有一些並未考慮到。
然後就是因為這個題目而認識了atoi()這個function
我以前居然不知道字串轉數字call function就好.....都是自己用來著
然後那個+-的沒有負負得正這麼回事,一次只能有一個+-號。


上一篇
Day13 LeetCode #7 Reverse Integer
下一篇
Day15 懺悔+LeetCode #9
系列文
有志者,事竟成。19
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言