Last active
April 13, 2022 16:58
-
-
Save svaza/6ff33d44817058a8941a10befdaad2f4 to your computer and use it in GitHub Desktop.
String to Integer (atoi)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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