LeetCode记录-easy-007Reverse Integer

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

class Solution {
    public int reverse(int x) {
        
    }
}

 

思路:先把数字求绝对值x,然后x%10取最后一位,然后ans = ans*10 + x%10,加上最后一位。然后x去掉最后一位。直到x = 0.要注意的时候,超出32位int类型的时候设置等于0就行了。

实现类:

class Solution {
    public static int reverse(int x) {
        int y = Math.abs(x);
        int a = y/100;
        int b = (y%100)/10;
        int c = y%10;
        int result = 0;
        if(x<0){
             result = -(c*100+b*10+a);
        }else{
             result = c*100+b*10+a;
        }
        return result;
    }
}

 后发现:如果数字大于三位,则输出错误。于是采用反转字符的方式实现:

class Solution {
    public static int reverse(int x) {
        int y = Math.abs(x);    //取绝对值
        String s = String.valueOf(y);    //int转string
        StringBuffer res = new StringBuffer(s);    //string转stringbuffer
        res=res.reverse();     //利用stringbuffer自带函数进行反转
        int result = Integer.valueOf(res.toString());    //转回int类型

if(x<0){ result = -result; } return result; } }

想到很多面试情况下不允许使用自带函数,使用拼接字符串方式:

class Solution {
    public static int reverse(int x) {
        int y = Math.abs(x);    //取绝对值
        String s = String.valueOf(y);    //int转string
        String res = "";
        for(int i = s.length()-1;i>=0;i--){
            res = res+s.charAt(i);
        }
        int result = Integer.valueOf(res);
        
if(x<0){ result = -result; } return result; } }

 

测试类:

import java.util.Scanner;

public class Test extends Solution{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入数字:");
        int in = input.nextInt();
        int out = reverse(in);
        System.out.println("输出为:"+out);
    }
}

 输出结果:

请输入数字:
-321
输出为:-123

 

posted on 2017-12-06 13:23  任性的大萝卜  阅读(81)  评论(0编辑  收藏  举报

导航