首页 > 其他 > 详细

8. String to Integer (atoi)

时间:2016-01-25 12:56:15      阅读:151      评论:0      收藏:0      [点我收藏+]

此题不难,主要在于你能否考虑到多种细节情况,下面总结如下

1.有空格  " 134 45"

2.有符号  " + 23 4"  "- 234"

3.有其他字符  "af+234"

4.超出临界值  "9223372036854775809"

代码如下:

 1     public static int atoi(String str) {
 2 
 3         if (str == null || str.trim().length() == 0) {
 4             return 0;
 5         }
 6         int i = 0;
 7 
 8         // 去空格
 9         str = str.trim();
10         // 符号
11         char flag = ‘+‘;
12         if (str.charAt(0) == ‘-‘) {
13             flag = ‘-‘;
14             i++;
15         } else if (str.charAt(0) == ‘+‘) {
16             flag = ‘+‘;
17             i++;
18         } else if (str.charAt(0) >= ‘0‘ && str.charAt(0) <= ‘9‘) {
19             flag = ‘+‘;
20         } else {
21             return 0;
22         }
23 
24         // 计算
25         double result = 0;
26         while (str.length() > i && str.charAt(i) >= ‘0‘ && str.charAt(i) <= ‘9‘) {
27             result = result * 10 + (str.charAt(i) - ‘0‘);
28             i++;
29         }
30 
31         if (flag == ‘-‘) {
32             result = -result;
33         }
34 
35         if (result > Integer.MAX_VALUE) {
36             result = Integer.MAX_VALUE;
37         }
38         if (result < Integer.MIN_VALUE) {
39             result = Integer.MIN_VALUE;
40         }
41 
42         return (int) result;
43     }

 

8. String to Integer (atoi)

原文:http://www.cnblogs.com/imyanzu/p/5156973.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!