【leetcode】8.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); } }

 

posted @ 2018-02-02 22:27  于淼  阅读(160)  评论(0编辑  收藏  举报