当前位置:   article > 正文

【Leecode】7 整数反转

【Leecode】7 整数反转

整数反转问题是很基础的一类问题。下面以leecode第七题拓展不同的题型与解法

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。 如果反转后整数超过 32 位的有符号整数的范围 [−231,
231 − 1] ,就返回 0。 假设环境不允许存储 64 位整数(有符号或无符号)。

示例 1: 输入:x = 123 输出:321

示例 2: 输入:x = -123 输出:-321 示例 3: 输入:x = 120 输出:21

示例 4: 输入:x = 0 输出:0

class Solution {
    public int reverse(int x) {
        long n = 0;
        while(x != 0) {
            n = n*10 + x%10;
            x = x/10;
        }
        return (int)n==n? (int)n:0;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

还有一种题目就是不限制返回值的大小。并且需要输出则可以采用数组形式保存数位的值的方法

class Solution {
    public void reverse(int x) {
        int i=0;
        int j,result=0;
        int[] a;
        if(x==0){
            System.out.print(0);
        }
        else{
            while(x>0){
                a[i] = x%10;
                i++;
                x = x/10;
            }
        }
        for(i=40;i>0;i--){
            if(a[i]!=0)
                j=i;
                break;
        }    
        for(i=0;i<=j;i++){
            System.out.print(a[i]);
        }

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/318749
推荐阅读
相关标签
  

闽ICP备14008679号