How to Reverse an Integer in Java

The challenge

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 store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

The solution

class Solution { // take in int, return int public int reverse(int x) { // set a Long variable to return // we make it a long incase we catch the edge case // of a larger size than int long out = 0; // loop while processing while(x!=0) { // multiple by 10 and add decimal place division out = out * 10 + x % 10; // move the decimal place by 1 x /= 10; } // return 0 if edge case found if (Integer.MAX_VALUE<out || out<Integer.MIN_VALUE) return 0; // return the output and cast to an int return (int)out; } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments