8. String to Integer (atoi)

Posted

tags:

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

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

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)的主要内容,如果未能解决你的问题,请参考以下文章

8. String to Integer (atoi)

8. String to Integer (atoi)

8. String to Integer (atoi)

8 String to Integer (atoi)

LeetCode - 8 - String to Integer (atoi)

leetcode-8. String to Integer (atoi)