Skip to content

Instantly share code, notes, and snippets.

@yanil3500
Last active December 1, 2017 18:34
Show Gist options
  • Save yanil3500/277df2408d2db60283b6ce597cf5e349 to your computer and use it in GitHub Desktop.
Save yanil3500/277df2408d2db60283b6ce597cf5e349 to your computer and use it in GitHub Desktop.
Reverse an Integer
class ReverseInteger {
public static int reverseInteger(int num){
long reversedNum = 0L;
while(num != 0){
//Calculate the remainder
reversedNum = (num % 10) + (reversedNum * 10);
//Recalculate num to remove digit from tens place
num = num / 10;
if (doesOverflow(reversedNum) || doesUnderflow(reversedNum)) {
return 0;
}
}
return (int)reversedNum;
}
public static boolean doesUnderflow(long num){
return num < -2_147_483_648;
}
public static boolean doesOverflow(long num){
return num > 2_147_483_647;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment