乘风破浪:LeetCode真题_008_String to Integer (atoi)

乘风破浪:LeetCode真题_008_String to Integer (atoi)

一、前言

   将整型转换成字符串,或者将字符串转换成整型,是经常出现的,也是必要的,因此我们需要熟练的掌握,当然也有很多工具来实现了,但是在这个基础上加入一些其他的因素就是考点的所在了。

二、String to Integer (atoi)

2.1 问题理解

2.2 问题分析和解决

    看到这个问题,我们就需要遍历字符串,然后判断开始的时候是不是空格,+,-,或者数字,如果不是的话就是不合理的,如果是,则继续向后遍历,直至遇到其他字符为止,将这之间的内容保存下来,并且转换成整型数据。如果发现大于整型的范围则根据正负返回相应的结果。

    我们的代码:

 1 public class Solution {
 2 
 3     public int myAtoi(String str) {
 4 
 5         if (str == null || str.length() == 0) {
 6                return 0;
 7         }
 8 
 9         // 如果字符串以空格开始
10         int start = 0; //从开始找第一个不是空格的数
11         boolean positive = true; // 是否为正数默认为true
12 
13         if (str.charAt(start) == ' ') {
14             while (str.charAt(start) == ' ') {
15                 start++;
16                 if (start >= str.length()) { // 输入的全是空格
17                     return 0;
18                 }
19             }
20         }
21 
22         if (str.charAt(start) == '-') { // 第一个非空白字符中-
23             positive = false;
24             start++;
25         } else if (str.charAt(start) == '+') {// 第一个非空白字符是+
26             start++;
27         } else if (str.charAt(start) >= '0' && str.charAt(start) <= '9') { // 第一个非空白字符是数字
28             return cal(str, start, true);
29         } else { // 其它情况就抛出异常
30             return 0;
31         }
32 
33         if (start >= str.length()) { // 第一个非空白字符是+或者-但也是最后一个字符
34             return 0;
35         }
36 
37         if (str.charAt(start) > '9' || str.charAt(start) < '0') { // +或者-后面接的不是数字
38             return 0;
39         } else {
40             return cal(str, start, positive);
41         }
42     }
43 
44     private int cal(String str, int start, boolean positive) {
45 
46         long result = 0;
47         while (start < str.length() && str.charAt(start) >= '0' && str.charAt(start) <= '9') {
48             result = result * 10 + (str.charAt(start) - '0');
49 
50             if (positive) { // 如果是正数
51                 if (result > Integer.MAX_VALUE) {
52                     return Integer.MAX_VALUE;
53                 }
54             } else {
55                 if (-result < Integer.MIN_VALUE) {
56                     return Integer.MIN_VALUE;
57                 }
58             }
59 
60             start++;
61         }
62 
63         if (positive) {
64             return (int) result;
65         } else {
66             return (int) -result;
67         }
68     }
69 }

三、总结

    通过这样的实践,使得我们对于一些细节上的东西有了更深刻的认识,比如越界问题,比如正负号问题,以及正负号之后是不是数字,空格等等的解决方法。

原文地址:https://www.cnblogs.com/zyrblog/p/10209829.html