Last active
December 1, 2017 18:34
-
-
Save yanil3500/277df2408d2db60283b6ce597cf5e349 to your computer and use it in GitHub Desktop.
Reverse an 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
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