Skip to content

Instantly share code, notes, and snippets.

@svaza
Last active April 13, 2022 16:58
Show Gist options
  • Select an option

  • Save svaza/6ff33d44817058a8941a10befdaad2f4 to your computer and use it in GitHub Desktop.

Select an option

Save svaza/6ff33d44817058a8941a10befdaad2f4 to your computer and use it in GitHub Desktop.
String to Integer (atoi)
public class Solution {
public int MyAtoi(string s) {
sbyte sign = 1;
int runningNumber = 0;
bool isReadNumber = false;
bool isOverflow = false;
for(int i = 0; i < s.Length; i++)
{
if(Char.IsWhiteSpace(s[i]) && !isReadNumber) continue;
else if(s[i] == '-' && !isReadNumber)
{
sign = -1;
isReadNumber = true;
}
else if(s[i] == '+' && !isReadNumber)
{
isReadNumber = true;
}
else if(Char.IsNumber(s[i]))
{
isReadNumber = true;
int currentInteger = (int)Char.GetNumericValue(s[i]);
long newSum = ((runningNumber * 10) + currentInteger);
if((newSum - currentInteger)/10 == runningNumber)
runningNumber = (int)newSum;
else
{
return sign == -1 ? Int32.MinValue: Int32.MaxValue;
}
}
else break;
}
return runningNumber * sign;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment