[Leetcode]8.String to Integer (atoi)

題目:

難度:中等

Implement atoi which converts a string to an integer.

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.

Note:

  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [?2^31, 2^31 ? 1]. If the numerical value is out of the range of representable values, INT_MAX (2^31 ? 1) or INT_MIN (?2^31) is returned.
Example 1:

Input: "42"
Output: 42

Example 2:

Input: " -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore INT_MIN (?2^31) is returned.

解釋下題目巧娱,給定一串字符串斟或,按一定的要求轉(zhuǎn)換成一個整數(shù)僚害。一定要把所有的要求都看清楚氏仗,不然test case 會有很多失敗的情況搀别。

  1. 從第一個非空格的字符開始算起碑隆,也就是前面的空格要trim掉
  2. 字符串可能含有任何字符猴贰,所以第一個非空字符可以是 +/- 或者數(shù)字麦轰,遇到其他的則停止
  3. 沒有有效的轉(zhuǎn)換淑倾,要輸出0
  4. 數(shù)字如果不處于 [?2^31, 2^31 ? 1] 之間馏鹤,則要輸出最大值或最小值,請參考例子5

個人感覺這道題的問題在于怎么樣包含所有可能的情況娇哆,有幾個重點的邊緣測試一定要考慮湃累,其他的問題應(yīng)該不是太難

Java Solution 1:

本人的辦法比較直接,沒有過多考慮時間碍讨,只是把所有能想到的case都cover住了治力。

public int myAtoi(String str) {
            final char[] acceptedArray = new char[]{'1','2','3','4','5','6','7','8','9','0'};
            final char[] acceptedSignedArray = new char[]{'1','2','3','4','5','6','7','8','9','0','+','-'};
            final int INT_MIN = Integer.MIN_VALUE;
            final int INT_MAX = Integer.MAX_VALUE;

            int num = 0;
            StringBuilder sb = new StringBuilder();

            //trim white space from str
            String trimedString = str.trim();

            if (trimedString == null || trimedString.length() == 0)
                return 0;

            char[] charArray = trimedString.toCharArray();

            //Retrieve the first char with Sign +/-
            char first = charArray[0];

            for(int i=0; i<acceptedSignedArray.length; i++ ){
                if (first == acceptedSignedArray[i]){
                    sb.append(first);
                    break;
                }
            }

            if(sb.length() == 0)
                return 0;

            for(int i = 1; i< charArray.length; i++){
                boolean bFound = false;
                for(int j=0; j<acceptedArray.length; j++ ){
                    if (charArray[i] == acceptedArray[j]){
                        sb.append(charArray[i]);
                        bFound = true;
                        break;
                    }
                }

                if(bFound == false)
                    break;

            }

        String s = sb.toString();
        //Filter sign only string
        if (s.equals("+") || s.equals("-"))
            return 0;

        //Filter out of int range string
        try {
            num = Integer.valueOf(s);
        }catch(NumberFormatException ex){
            if (s.indexOf("-") >= 0)
                return INT_MIN;

            return INT_MAX;
        }

        return num;
    }
image.png

下面給出別人的解法

劃重點:

1.通過運算來生成整數(shù),我是用string轉(zhuǎn)換
2.通過第一位是不是符號來決定是從 0勃黍, 還是1 開始循環(huán)宵统,而我是單獨把第一位取出來

  1. 通過 1和-1來覺得 符號的正負,這個想法不錯覆获。
  2. 判斷數(shù)字马澈,可以直接用 大小判斷, chars[i] < '0' || chars[i] > '9'
public int myAtoi2(String str) {
        if (str == null) return 0;

        str = str.trim();
        if(str.length() == 0) return 0;

        char[] chars = str.toCharArray();

        // check if the 1st character is valid, i.e. must be a sign or a number
        if(chars[0] != '-' && chars[0] != '+' && chars[0] < '0' || chars[0] > '9') return 0;

        long sum = 0;
        int i = (chars[0] == '+' || chars[0] == '-') ? 1 : 0;
        int sign = chars[0] == '-' ? -1 : 1;
        for(; i < chars.length; i++){
            if(chars[i] < '0' || chars[i] > '9') break;
            else sum = sum * 10 + (chars[i] - '0');

            if(sum > Integer.MAX_VALUE && sign == 1)  return Integer.MAX_VALUE;
            if(sum > (long)Integer.MAX_VALUE + 1 && sign == -1) return Integer.MIN_VALUE;
        }

        return (int)sum * sign;

    }

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末弄息,一起剝皮案震驚了整個濱河市箭券,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌疑枯,老刑警劉巖辩块,帶你破解...
    沈念sama閱讀 222,104評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異荆永,居然都是意外死亡废亭,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評論 3 399
  • 文/潘曉璐 我一進店門具钥,熙熙樓的掌柜王于貴愁眉苦臉地迎上來豆村,“玉大人,你說我怎么就攤上這事骂删≌贫” “怎么了?”我有些...
    開封第一講書人閱讀 168,697評論 0 360
  • 文/不壞的土叔 我叫張陵宁玫,是天一觀的道長粗恢。 經(jīng)常有香客問我,道長欧瘪,這世上最難降的妖魔是什么眷射? 我笑而不...
    開封第一講書人閱讀 59,836評論 1 298
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上妖碉,老公的妹妹穿的比我還像新娘涌庭。我一直安慰自己,他們只是感情好欧宜,可當(dāng)我...
    茶點故事閱讀 68,851評論 6 397
  • 文/花漫 我一把揭開白布坐榆。 她就那樣靜靜地躺著,像睡著了一般冗茸。 火紅的嫁衣襯著肌膚如雪猛拴。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,441評論 1 310
  • 那天蚀狰,我揣著相機與錄音,去河邊找鬼职员。 笑死麻蹋,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的焊切。 我是一名探鬼主播扮授,決...
    沈念sama閱讀 40,992評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼专肪!你這毒婦竟也來了刹勃?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,899評論 0 276
  • 序言:老撾萬榮一對情侶失蹤嚎尤,失蹤者是張志新(化名)和其女友劉穎荔仁,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體芽死,經(jīng)...
    沈念sama閱讀 46,457評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡乏梁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,529評論 3 341
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了关贵。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片遇骑。...
    茶點故事閱讀 40,664評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖揖曾,靈堂內(nèi)的尸體忽然破棺而出落萎,到底是詐尸還是另有隱情,我是刑警寧澤炭剪,帶...
    沈念sama閱讀 36,346評論 5 350
  • 正文 年R本政府宣布练链,位于F島的核電站,受9級特大地震影響奴拦,放射性物質(zhì)發(fā)生泄漏兑宇。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,025評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望隶糕。 院中可真熱鬧瓷产,春花似錦、人聲如沸枚驻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽再登。三九已至尔邓,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間锉矢,已是汗流浹背梯嗽。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留沽损,地道東北人灯节。 一個月前我還...
    沈念sama閱讀 49,081評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像绵估,于是被迫代替她去往敵國和親炎疆。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,675評論 2 359