Solution using Java 8


  • 1
    S
    public class Solution {
        public int reverse(int x) {
            int r = 0;
            while (x!=0) {
                try{
                    r = Math.multiplyExact(r,10);
                    r = Math.addExact(r, x%10);
                }
                catch (ArithmeticException e){
                    return 0;
                }
                x = x/10;
            }
            return r;
        }
    }

  • 0
    public int reverse(int x) {
    
    String s = String.valueOf(x);
    StringBuffer r = new StringBuffer();
    for(int i=s.length()-1;i>0;i--){
        r.append(s.charAt(i));
    }
    
    if(Character.isDigit(s.charAt(0))){
        r.append(s.charAt(0));
    } else {
        r.insert(0,s.charAt(0));
    }
    System.out.println(r.toString());
    long rl = Long.valueOf(r.toString());
    if(rl > Integer.MAX_VALUE || rl < Integer.MIN_VALUE) return 0;
    return (int)rl;
    

    }


  • 0
    D
    public class Solution {
        public int reverse(int x) {
             long a=x;
    		if (x < 10 && x >-10)
    			return x;
    		else {
    			 if(x<=-10)
    				 a*=-1;
    				int max = Integer.MAX_VALUE;
    				long newX = 0l;
    				String X = String.valueOf(a);
    				char[] reX = new char[X.length()];
    				for (int j = 0, i = X.length() - 1; i >= 0 && j < X.length(); i--, j++) {
    					reX[j] = X.charAt(i);
    				}
    				newX = Long.parseLong(String.valueOf(reX));
    				if (newX <= max) {
    					if(x<=-10)
    						return (int) newX*-1;
    					return (int) newX;
    				} else {
    					return 0;
    				}
    			}
    		
    		
        }
    }

Log in to reply
 

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