Leetcode8>String to Integer(实现字符串到整数的转换)

题目: 实现字符串到整数的转换

解题思路:

下面给出这道题应该注意的一些细节:

1. 字符串“    123   ” = 123;

2.   字符串“+123” = 123;

3.   字符串“-123” = -123;

4.   字符串“-” = 0;“+” = 0;

5.   字符串“123-” = 123;

6.   字符串“21474836478” = 2147483647(Integer.MAX_VALUE)

7.   其余情况都是非法输入,一律返回0;

代码如下:

 1 public class Solution {
 2     public int myAtoi(String str) {
 3         if(str == null || str.length() < 1)
 4             return 0;
 5         boolean negative = false;
 6         int i = 0;
 7         double res = 0.0;
 8         String s = str.trim();
 9         int length = s.length();
10         if(s.charAt(i) < '0'){
11             if(s.charAt(i) == '-'){
12                 negative = true;
13             }
14             else if(s.charAt(i) != '+'){
15                 return 0;
16             }
17             if(length == 1)
18                 return 0;
19             i++;
20         }
21         while(i < length){
22             int n = (s.charAt(i) - '0') ;
23             if(n >= 0 && n <= 9){
24                 res *= 10;
25                 res += n;
26                 i ++;
27             }
28             else
29                 break;
30 
31         }
32         if(negative){
33             res *= -1;
34         }
35         res = res >= Integer.MAX_VALUE ? Integer.MAX_VALUE : res;
36         res = res <= Integer.MIN_VALUE ? Integer.MIN_VALUE : res;
37         return (int)res;
38     }
39 }
原文地址:https://www.cnblogs.com/leavescy/p/5878970.html