Created
February 1, 2013 03:42
-
-
Save daifu/4689019 to your computer and use it in GitHub Desktop.
Implement atoi to convert a string to an integer.
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 atoi(String str) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| // string start with - | |
| // string is overflow the Integer.MAX_VALUE | |
| if(str.length() == 0) return 0; | |
| int right = str.length() - 1; | |
| int res = 0; | |
| int digit = 1; | |
| if(right == 0){ | |
| return str.charAt(right) - '0'; | |
| } | |
| while(right >= 0){ | |
| char c = str.charAt(right); | |
| //System.out.println(res); | |
| if(c == '+') { | |
| right--; | |
| } else if (c == '-'){ | |
| res *= -1; | |
| right--; | |
| } else if (('0' <= c) && (c <= '9')) { | |
| //System.out.println(c); | |
| res += ((c - '0') * digit); | |
| digit *= 10; | |
| right--; | |
| } else { | |
| right--; | |
| } | |
| } | |
| return res; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment