Solution in Java for reverse signed string


  • 0
    S
    class Solution {
        public int reverse(int x) {
            boolean isNegative = false;
            int num = 0;
            long reverse = 0;
            if(x < 0) {
                num = -x;
                isNegative = true;
            } else{
                num = x;
            }
            
            while(num != 0) {
                reverse = reverse * 10 + (num % 10);
                num = num / 10;
            }
            
            if(isNegative)
                reverse = -reverse;
            
            if(reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE)
                return 0;
            return (int)reverse;        
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.