-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertStringToInteger.cs
More file actions
58 lines (51 loc) · 1.74 KB
/
ConvertStringToInteger.cs
File metadata and controls
58 lines (51 loc) · 1.74 KB
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
57
58
namespace CodeChallenge
{
public class ConvertStringToInteger
{
public int ConvertingStringToInteger(string input)
{
//Initializing the boundaries given in the question
int minInt = int.MinValue;
int maxInt = int.MaxValue;
int index = 0;
int result = 0;
int sign = 1;
int length = input.Length;
//To Skip leading whitespaces as required
while (index < length && input[index] == ' ')
{
index++;
}
//To Check for the sign of the number inputed
if (index < length && (input[index] == '+' || input[index] == '-'))
{
if (input[index] == '-')
{
sign = -1;
}
else
{
sign = 1;
}
index++;
}
//To Convert each digits to integer
while (index < length && char.IsDigit(input[index]))
{
//Then Convert character to its integer value
int digit = input[index] - '0';
//To Check for potential overflow as expected in Question
if (result > (maxInt - digit) / 10)
{
// If adding this digit causes overflow, return the appropriate limit
Console.WriteLine("Overflow detected! Returning the closest boundary value.");
return (sign == 1) ? maxInt : minInt;
}
// Update result with the new digit
result = result * 10 + digit;
index++;
}
return result * sign;
}
}
}