【LeetCode-数字】反转整数

题目来源于 LeetCode 上第 7号(Reverse Integer)问题,题目难度为 Easy,AC率25.4%git

题目地址:https://leetcode.com/problems/reverse-integer/面试

题目描述

Given a 32-bit signed integer, reverse digits of an integer.算法

给定一个32位带符号整数,反转整数数组

Example 1:
    Input: 123
    Output: 321

Example 2:
    Input: -123
    Output: -321

Example 3:
    Input: 120
    Output: 21
复制代码

Note:bash

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.函数

假设只能存储32位带符号整数范围内的整数:[- 2 ^31 , 2 ^31 - 1]。假设函数在反向整数溢出时返回0。post

题目解析

  • 整数x的取值范围是:-2 ^31 ~ 2 ^31 - 1(-2147483648~2147483647),假设咱们输入的整数是1234567899,reverse后就变成了9987654321,超出int最大范围,也就会出现越界错误,因此咱们应该定义一个long型的变量sum来存储反转以后的数字ui

  • 经过不断的取余运算,从整数的末尾开始,一位一位的移动生成新的数字this

算法效率以下: spa

代码实现

public int reverse(int x) {
    long sum = 0;
    while(x != 0){
        sum = sum*10 + x%10;
        x = x/10;
        if(sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) return 0;
    }
    return (int)sum;
}
复制代码

相关文章

【LeetCode-数组】查找大多数元素

【LeetCode-数组】数组式整数加法

【LeetCode-栈】有效的括号

【LeetCode-链表】面试题-反转链表

【LeetCode-二叉树】二叉树前序遍历

相关文章
相关标签/搜索