String to Integer 字符转换

  这道题应该属于简单范畴,很容易理解,数字的表示方法无非两种

1,不带符号的 123

2,带符号的,+123,-123

理解了这个基本没啥问题了,另外鉴于int类型,正数范围和负数范围不完全一致,所以要注意先判断负数,在判断正数。

代码如下:

 1 public class Solution {
 2      public int MyAtoi(string str)
 3         {
 4             var temp = str.Trim(new char[] { ' ' });
 5             long num = 0;
 6             var a = 1;
 7             if (temp.StartsWith("-") || temp.StartsWith("+"))
 8             {
 9                 if (temp.StartsWith("-"))
10                 {
11                     a = -1;
12                 }
13                 temp = temp.Substring(1);
14             }
15             for (int i = 0; i < temp.Length; i++)
16             {
17                 int b = 0;
18                 if (int.TryParse(temp[i].ToString(), out b))
19                 {
20                     num = num * 10 + b;
21                       if (a < 0)
22                     {
23                         if (a * num < int.MinValue)
24                         {
25                             num = int.MinValue;
26                             break;
27                         }
28                         
29                     }
30                     else if (num > int.MaxValue)
31                     {
32                         num = int.MaxValue;
33                         break;
34                     }
35                 }
36                 else
37                 {
38                     break;
39                 }
40             }
41             if (num > int.MinValue)
42             {
43                 num = num * a;
44             }
45             return (int)num;
46         }
47 }
View Code

期待你得评论,你得评论和支持是我最大的动力!

原文地址:https://www.cnblogs.com/tomguo/p/8550780.html