美文网首页
7. 反转整数

7. 反转整数

作者: yahibo | 来源:发表于2019-03-13 18:02 被阅读0次

难度:简单
给定一个 32 位有符号整数,将整数中的数字进行反转。

示例1:输入123 输出 321
示例2:输入-123 输出-321
示例3:输入120 输出21
若反转后整数溢出返回0

复杂度分析
时间复杂度:O(log⁡(x)),x中大约有log10(x)位数字。
空间复杂度:O(1)。

Java实现:

public static int reverse(int x) {
    int result = 0;
    while(x!=0) {
    int push = x%10;
    x /= 10;
    if(result>Integer.MAX_VALUE/10||(result==Integer.MAX_VALUE/10&&push>7)) return 0;
    if(result<Integer.MIN_VALUE/10||(result==Integer.MIN_VALUE/10&&push>8)) return 0;
        result = result*10+push;
    }
    return result;
}

C语言实现:

int main(int argc, const char * argv[]) {
    int result = reverse(1534236469);
    printf("%d",result);
    printf("\n");
    return 0;
}
int reverse(int x) {
    int result = 0;
    while (x!=0) {
        int push = x%10;
        x /= 10;
        if (result>(pow(2,31)-1)/10||(result==(pow(2,31)-1)/10&&push>7))return 0;
        if (result<-pow(2,31)/10||(result==-pow(2,31)/10&&push>8))return 0;
        result = result*10+push;
    }
    return result;
}

相关文章

  • Leecode: 7.整数反转

    在刷Leecode, 7.整数反转思路:将整数转为string后反转,再使用int()转回整数可以顺利提交代码,但...

  • [day1] [LeetCode] [title7,9]

    7. 反转整数 给定一个 32 位有符号整数,将整数中的数字进行反转。 示例1: 输入: 123 输出: 321 ...

  • 7. 反转整数

    20180919-摘抄自7. 反转整数 给定一个 32 位有符号整数,将整数中的数字进行反转。 示例 1: 输入:...

  • 算法练习四

    7. 反转整数 给定一个 32 位有符号整数,将整数中的数字进行反转。 示例 1: 输入: 123输出: 321示...

  • LeetCodeDay07 —— 反转整数&字符串中的第一个唯一

    7. 反转整数 描述 给定一个 32 位有符号整数,将整数中的数字进行反转。 示例 注意 假设我们的环境只能存储 ...

  • 7.反转整数

    给定一个 32 位有符号整数,将整数中的数字进行反转。 示例 1: 示例 2: 示例 3: 注意:假设我们的环境只...

  • 7. 反转整数

    给定一个 32 位有符号整数,将整数中的数字进行反转。 示例 1:输入: 123输出: 321 示例 2:输入: ...

  • 7.反转整数

    题目 思路1.判断范围2.反向生成数字代码

  • 7. 反转整数

    一、题目原型: 给定一个 32 位有符号整数,将整数中的数字进行反转。输入: 123输出: 321输入: -123...

  • 7. 反转整数

    内容 给定一个 32 位有符号整数,将整数中的数字进行反转。 示例 1: 输入: 123输出: 321示例 2: ...

网友评论

      本文标题:7. 反转整数

      本文链接:https://www.haomeiwen.com/subject/iuitmqtx.html