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);
    }
}

源码地址:

源码解答

猜你喜欢

转载自blog.csdn.net/wj903829182/article/details/83316564
今日推荐