leetcode8.String to Integer (atoi)

Posted 于淼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode8.String to Integer (atoi)相关的知识,希望对你有一定的参考价值。

8. String to Integer (atoi)

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.

Tips: 本题要自己实现atoi函数,需要声明的包括:

①.java 字符串或者字符数组结尾处并不包含"\0".

②考虑输入的字符串前面有很多空格。

③考虑‘+‘,‘_‘

④我没通过的case有"    -12a42",正确输出为 -12。

  "2147483648" 正确输出为 2147483647

 

package medium;

public class L8StringToInteger_atoi {

    public int myAtoi(String str) {
        if (str == "")
            return 0;
        long num = 0;
        int minus = 1;// +
        int i = 0;
        int len = str.length();
        while (i < len) {
            if (str.charAt(i) == ‘ ‘) {
                i++;
            }else{
          break;
       } }
if (str != null && i < len) { if (str.charAt(i) == ‘+‘) { minus = 1; i++; } else if (str.charAt(i) == ‘-‘) { minus = -1; i++; } while (i < len) { System.out.println(i + " " + str.charAt(i)); if (str.charAt(i) >= ‘0‘ && str.charAt(i) <= ‘9‘) { num = num * 10 + minus * (str.charAt(i) - ‘0‘); if ((minus == 1 && num >= 2147483647) ) { num = 2147483647; break; }if( (minus == -1 && num < -2147483648)){ num=-2147483648; break; } i++; System.out.println(i); } else { break; } } } return (int) num; } public static void main(String[] args) { String str = " -0012a42"; L8StringToInteger_atoi l8 = new L8StringToInteger_atoi(); int num = l8.myAtoi(str); System.out.println(num); } }

 



以上是关于leetcode8.String to Integer (atoi)的主要内容,如果未能解决你的问题,请参考以下文章

leetcode8.String to Integer (atoi)

LeetCode8. String to Integer (atoi)

LeetCode8. String to Integer (atoi)

leetcode8. String to Integer (atoi)

Leetcode8 String to Integer(atoi)

LeetCode8. String to Integer (atoi) 字符串转整数