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

Leetcode:String to Integer (atoi)

时间:2017-06-10 21:32:53      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:log   false   pre   return   long   positive   ted   默认   nbsp   

题目大意是要求我们实现自己的atoi方法,这个方法将字符串转换为32位整数。主要要应对以下几种特殊情况:

1.允许传入字符串开头存在若干空格字符,需要忽略这些字符。比如"  123",解析得到123;

2.忽略前端空白字符后,可能会跟随可选的+或-号表示整数的符号。比如"  +123",解析得到123;

3.在有效数值字符的后端,可以跟随任意无效的字符(比如@,#,$,a-z等),需要忽略所有的后续字符。比如" +123haha21",,解析得到123;

4.如果整个字符串并没有上面提到的有效部分(开始的+-符号以及后续的0~9),那么就返回0。比如"",解析得到0。

5.如果最终解析得到的字符串超过了32位整数的表示范围,那么对于过大值裁剪为最大的32位int值,过小值裁剪为最小的32位int值。比如"123456789123456",对应0x7fffffff;


 很恶心的题目,需要考虑到比较多的情况,而且现在的主流编程语言都有异常处理机制了,为什么还需要返回默认值这种简陋的方式呢。

时间复杂度是O(n),n是字符串的长度。伪代码也不太想给,各位自己看看描述就能写出来了。


 附上代码:

技术分享
 1 package cn.dalt.leetcode;
 2 
 3 /**
 4  * Created by dalt on 2017/6/10.
 5  */
 6 public class StringtoInteger {
 7     public int myAtoi(String str) {
 8         int v = 0;
 9         boolean positive = true;
10         int rpos = 0;
11         for (int bound = str.length(); rpos < bound && str.charAt(rpos) == ‘ ‘; rpos++) ;
12         if (str.length() == rpos) {
13             return 0;
14         }
15         if (str.charAt(rpos) == ‘+‘) {
16             positive = true;
17             rpos++;
18         } else if (str.charAt(rpos) == ‘-‘) {
19             positive = false;
20             rpos++;
21         }
22 
23         long value = 0;
24         for (int bound = str.length(); rpos < bound; rpos++) {
25             char c = str.charAt(rpos);
26             if (c < ‘0‘ || c > ‘9‘) {
27                 break;
28             }
29             value = value * 10 + c - ‘0‘;
30             if (value > Integer.MAX_VALUE) {
31                 return positive ? Integer.MAX_VALUE : Integer.MIN_VALUE;
32             }
33         }
34         value = positive ? value : -value;
35         return (int) Math.min(Math.max(value, Integer.MIN_VALUE), Integer.MAX_VALUE);
36     }
37 }
View Code

 

Leetcode:String to Integer (atoi)

标签:log   false   pre   return   long   positive   ted   默认   nbsp   

原文地址:http://www.cnblogs.com/dalt/p/6979732.html

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