You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* Given a 32-bit signed integer, reverse digits of an integer.
* Example 1:
* Input: 123
* Output: 321
*
* Example 2:
* Input: -123
* Output: -321
*
* Example 3:
* Input: 120
* Output: 21
*
* Note:
* Assume we are dealing with an environment which could only hold integers within
* the 32-bit signed integer range. For the purpose of this problem, assume that your
* function returns 0 when the reversed integer overflows.
*/
class Solution {
public int reverse(int x) {
int digits = Integer.toString(x).length();
int reversedNum = 0;
if(x < 0){ //dont want to count extra digit for '-' if negative
digits--;
}
while(digits>0){ //If number is 9463847412, this wont work - number will be 2147483640 = not overflow, then + 9 == overflow and //second two conditions check this edge case