-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringToInt.cc
61 lines (53 loc) · 1.44 KB
/
stringToInt.cc
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
59
60
61
#include <string>
#include <cctype>
#include <iostream>
#include <limits>
using namespace std;
class Solution {
private:
const int CONVERSATION_NUMBER = 48;
bool addCharToInt(long& result, const char& charToAdd){
result = result*10+static_cast<int>(charToAdd)-Solution::CONVERSATION_NUMBER;
if (result>INT_MAX){
return true;
}
return false;
}
int clampConvert(long arg){
arg= arg<INT_MIN? INT_MIN: arg;
arg= arg>INT_MAX? INT_MAX: arg;
return static_cast<int>(arg);
}
public:
int myAtoi(string s) {
bool isFirstNumberFound = false;
int sign = 1;
long ret = 0;
//string numberStr = "";
bool isReadStarted = false;
for(auto c:s){
if(isdigit(c)){
isFirstNumberFound = true;
bool isOverflow= addCharToInt(ret, c);
if(isOverflow){
break;
}
//numberStr += c;
}
else if(!isFirstNumberFound){
if(c == ' '){continue;}
else if(c =='-' || c=='+'){
sign = (c=='-')? -1: 1;
isFirstNumberFound = true;
//numberStr += c;
continue;
}
break;
}
else{
break;
}
}
return clampConvert(sign*ret);
}
};