码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】8.String to Integer (atoi)

时间:2018-02-03 00:42:45      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:new   package   min   imp   class   elf   problem   require   minus   

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

 

【leetcode】8.String to Integer (atoi)

标签:new   package   min   imp   class   elf   problem   require   minus   

原文地址:https://www.cnblogs.com/yumiaomiao/p/8407300.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!