Last active
August 29, 2015 14:09
-
-
Save fever324/1a79b8ca30b87a8c2d7c to your computer and use it in GitHub Desktop.
Reverse Integer
This file contains 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 Solution1 { | |
public int reverse(int x) { | |
if(x < 10 && x > -10){ | |
return x; | |
} | |
boolean negative = x < 0; | |
char[] c = null; | |
if(negative) { | |
c = (x+"").substring(1).toCharArray(); | |
} else { | |
c = (x+"").toCharArray(); | |
} | |
char temp; | |
for(int i = 0; i < c.length/2; i++) { | |
temp = c[i]; | |
c[i] = c[c.length - 1 -i]; | |
c[c.length -1 -i] = temp; | |
} | |
String s = String.valueOf(c); | |
return negative ? -Integer.parseInt(s) : Integer.parseInt(s); | |
} | |
} | |
public class Solution { | |
public int reverse(int x) { | |
int newX = 0; | |
while(x != 0) { | |
newX *= 10; | |
newX += x %10; | |
x /= 10; | |
} | |
return newX; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment