Skip to content

5. Reverse Integer

难度: Easy

刷题内容

原题连接

  • https://leetcode-cn.com/problems/reverse-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


解题方案

思路 1 **- 时间复杂度: O(n)*- 空间复杂度: O(1)***

将整数翻转,翻转后是否溢出了, beats 95.35%

class Solution {
    public int reverse(int x) {
        // 使用一个long型变量来保存
        long index = 0;
        while (x != 0){
            index = index * 10 + x %10;
            x = x / 10;
        }
        int result = (int) index;
        if(result != index){
            return 0;
        }
        return (int)index;
    }
}


回到顶部