1. 程式人生 > >8-string-to-integer-atoi

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: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) 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 (−231) is returned.

題目解答:

package com.jack.algorithm;

/**
 * create by jack 2018/10/23
 *
 * @auther jack
 * @date: 2018/10/23 22:13
 * @Description:
 * 字串轉換為整數
 */
public class StringToIntegerAtoi {

    /**
     * 題目描述:
     * https://leetcode.com/problems/string-to-integer-atoi/
     * @param str
     * @return
     */
    public static int myAtoi(String str) {
        //如果為null則直接返回
        if (str == null) {
            return 0;
        }
        //去掉字串前後空格
        str=str.trim();
        if ("".equals(str)) {
            return 0;
        }
        //正負數標誌,整數位true,負數為false,預設為true
        boolean flag = true;
        String s = "";
        int length = str.length();
        for (int i=0;i<length;i++) {
            //獲取字串的字元
            char c = str.charAt(i);
            //把字元轉換為對應的數字
            int n = c-48;
            //判斷字串第一個字元是負號(-),還是正號(+)
            if (i == 0 && c =='-') {
                flag = false;
            } else if (i == 0 && c == '+') {
                flag = true;
            }
            //判斷是否是0-9的數字
            if (n >= 0 && n < 10) {
                //字元拼接,方便後面轉換為數字
                s = s + c;
            } else if (i == 0 && (c == '-' || c=='+')) {
                //判斷第一個字元是否是加號或者減號,如果是則繼續
                continue;
            } else {
                //如果字元不是數字,或者第一個字元不是減號或者加號則跳出迴圈
                break;
            }
        }
        //如果為空這直接返回0
        if ("".equals(s)) {
            return 0;
        }
        int length1 = s.length();
        long sum = 0;
        //字串轉換為int
        for (int i=0;i<length1;i++) {
            char c = s.charAt(i);
            int n = c-48;
            sum = sum *10+n;
            //如果是正數
            if (flag) {
                //大於Integer.MAX_VALUE,則直接返回Integer.MAX_VALUE
                if (sum > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                }
            } else if (-sum < Integer.MIN_VALUE){
                //如果-sum小於Integer.MIN_VALUE,則直接返回Integer.MIN_VALUE
                return Integer.MIN_VALUE;
            }
        }
        if (!flag) {
            sum = -sum;
        }
        int rs =0;
        rs = (int) sum;
        return rs;
    }

    public static void main(String[] args) {
        //數字字元減去48得到數字
        int a = 'a'-48;
        int b = -2;
        //System.out.println(a);
        int n = myAtoi("9223372036854775808");
        System.out.println("n="+n);
        //int c = '.' - 48;
        //System.out.println(c);
    }
}

原始碼地址:

原始碼解答