mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
Leetcode day 2 and 3
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
class Solution {
|
||||
public:
|
||||
int myAtoi(string s) {
|
||||
if(s.empty()) return 0;
|
||||
|
||||
const long long MAX_INT = INT_MAX;
|
||||
const long long MIN_INT = INT_MIN;
|
||||
|
||||
int n = s.length();
|
||||
int i = 0;
|
||||
while(i<n && s[i]==' ')
|
||||
i++;
|
||||
if(i==n)
|
||||
return 0;
|
||||
int sign = 1;
|
||||
if(s[i]=='+')
|
||||
i++;
|
||||
else if(s[i]== '-'){
|
||||
sign = -1;
|
||||
i++;
|
||||
}
|
||||
|
||||
long long res= 0;
|
||||
while(i<n && isdigit(s[i])){
|
||||
int digit = s[i] - '0';
|
||||
res = res*10 + digit;
|
||||
|
||||
if(sign*res >= MAX_INT)
|
||||
return MAX_INT;
|
||||
if(sign*res <= MIN_INT)
|
||||
return MIN_INT;
|
||||
i++;
|
||||
}
|
||||
return sign*res;
|
||||
}
|
||||
|
||||
};
|
||||
Reference in New Issue
Block a user