-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8 String to Integer (atoi).cs
56 lines (44 loc) · 1.53 KB
/
8 String to Integer (atoi).cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class Solution {
public int MyAtoi(string s) {
//Enumeration variable.
int idx = 0;
//Variable to store result.
long result = 0;
//Boolean to decide sign.
bool isNeg = false;
//Untill there are white spaces, keep incrementing.
while(idx < s.Length && char.IsWhiteSpace(s[idx])) idx++;
//If we encounter sign, change boolean value and increment.
if (idx < s.Length && (s[idx] == '-' || s[idx] == '+')) {
isNeg = s[idx] == '-';
idx++;
}
//Untill we keep encountering digits, keep adding it to result.
while(idx < s.Length && char.IsDigit(s[idx])) {
//Converting characters to numbers.
result = result * 10 + s[idx] - '0';
//If value exceeds MaxValue, break the loop.
if(result > int.MaxValue) break;
//Keep incrementing index.
idx++;
}
//If value needs to be negative, convert it.
result = isNeg ? -result : result;
//If values are max, return MaxValue.
if (result > int.MaxValue)
result = int.MaxValue;
//If values are min, return MinValue.
if (result < int.MinValue)
result = int.MinValue;
//Parse it to integer and return.
return (int)result;
}
}
class Program
{
static void Main(string[] args)
{
Solution sol = new Solution();
Console.WriteLine(sol.MyAtoi("4193 with words"));
}
}