File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < string>
2
+ #include < iostream>
3
+ #include < climits>
4
+
5
+ int stringToInteger (const std::string& str)
6
+ {
7
+ int result = 0 ;
8
+ bool isNegative = false ;
9
+ int i = 0 ;
10
+
11
+ // check str is negative or not
12
+ if (str[0 ] == ' -' )
13
+ {
14
+ isNegative = true ;
15
+ i++;
16
+ }
17
+
18
+ for (; i<str.size (); ++i)
19
+ {
20
+ if (std::isdigit (str[i]))
21
+ {
22
+
23
+ // to check the overflow is exist or not
24
+ // if INT_MAX > (result * 10 + (str[i] - '0')) then there is a overflow
25
+ // if(result * 10 + (str[i] - '0') > INT_MAX) // but this will not work
26
+ // because result * 10 + (str[i] - '0') if result is cause overflow then there
27
+ // will be undefined behaviour so it is good idea to compare it with result
28
+
29
+ if (result > (INT_MAX - (str[i] - ' 0' )) / 10 )
30
+ {
31
+ std::cout<<" overflow detected" <<std::endl;
32
+ return isNegative ? INT_MIN : INT_MAX;
33
+ }
34
+
35
+ result = result * 10 + (str[i] - ' 0' );
36
+ }
37
+ else
38
+ return 0 ;
39
+ }
40
+
41
+ if (isNegative)
42
+ result = -result;
43
+
44
+ return result;
45
+ }
46
+
47
+ int main ()
48
+ {
49
+ std::cout<<stringToInteger (" 123" )<<std::endl;
50
+ std::cout<<stringToInteger (" 99999999999999999999999999" );
51
+
52
+ std::endl (std::cout);
53
+
54
+ return 0 ;
55
+ }
You can’t perform that action at this time.
0 commit comments