Leetcode 007 Reverse Integer 整数翻转

题目

链接   

英文原文

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

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

我的翻译

官方中文版链接

给定一个32位带符号(signed,即确定正负号)整数,返回翻转后的值。

注解:
假定我们只能处理32位带符号整数。你的函数需要在溢出时返回0。

样例

Example 1:

Input: 123
Output:  321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

我的解法

思路分析

翻转整数部分没什么可说的,只需要根据两个数学知识: num%10 得到 num的个位数 , num / 10得到的是num去除个位以后的数字,即可。

重点在于溢出判断,我的做法是判断 (num*10)/10 == num , 如果不等于,则说明 num * 10 已经溢出,此时返回0即可。

AC代码

class Solution {
public:
    int reverse(int x) {
        int Ispos = 1;//ispostive是否正数,负数化为正数处理
        if ( x < 0){
            Ispos = 0;
            x = -x;
        }
        int ans = 0;
        while(x){
            ans += x % 10;
            x = x / 10;
            if (x) {
                int ans1 = ans;
                ans *= 10;
                if ( ans1 != ans / 10){
                    return 0;
                }
            }
           
        }

        if( Ispos){
            return ans;
        }else{
            return -ans;
        }


    }
};

时间:22ms

他人代码赏析

他的代码的优化之处在于溢出判断。并没有采用int声明变量,而是long。然后判断结果和int机内最大最小值比较。具体算法实现思想并没有改进,因此时间并没有优化很多。实际上这个问题O(n)已经是最小时间复杂度了。毕竟翻转整数总要把整个整数扫描一遍吧。

static int x = []() { 
    std::ios::sync_with_stdio(false); 
    cin.tie(NULL);  
    return 0; 
}();

class Solution {
public:
    int reverse(int x) {
        long answer = 0;
        while (x != 0) {
            answer = answer * 10 + x % 10;
            if (answer > INT_MAX || answer < INT_MIN) return 0;
            x /= 10;
        }
        return (int)answer;
    }
};

时间:9ms

说明:本文除注明外,全文原创。也在我的个人博客上发布:https://www.watwg.com/

本题地址:https://www.watwg.com/leetcode/reverseinteger/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
题目描述: 请你来实现一个 atoi 函数,使其能将字符串转换成整数。该函数需要丢弃无用的开头空格,找到第一个非空格字符,然后将其后面的字符(如果符合要求的话)转换成整数,如果第一个非空字符为正或者负号时,将该符号与后面尽可能多的连续数字组合起来,返回整数。如果第一个非空字符是非数字字符或者一开始没有给定任何数字,则返回 0。 注意: 假如只能存储有限的整数范围内,例如32位整数,则请返回 INT_MAX(231 − 1)或 INT_MIN(−231)。 示例: 输入: "42" 输出: 42 输入: " -42" 输出: -42 解释: 第一个非空白字符为 '-', 它是一个负号。我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。 输入: "4193 with words" 输出: 4193 解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。 输入: "words and 987" 输出: 0 解释: 第一个非空字符是 'w', 但它不是数字或正、负号。因此无法执行有效的转换。 输入: "-91283472332" 输出: -2147483648 解释: 数字 "-91283472332" 超过 32 位有符号整数范围。因此返回 INT_MIN(−231)。 解题思路: 这道题比较繁琐,需要注意的地方很多,需要仔细考虑每一种情况。下面是一种比较清晰的思路: 1. 删除字符串前面的空格。 2. 判断第一个非空字符是否为正负号或数字,如果是数字则开始转换,否则直接返回0。 3. 转换过程中如果遇到非数字字符,则停止转换,返回当前已转换的数字。 4. 判断转换后的数字是否超出了32位有符号整数的范围,如果超出了则返回对应的极值。 代码实现: ```python class Solution: def myAtoi(self, str: str) -> int: # 删除字符串前面的空格 str = str.lstrip() # 判断第一个非空字符是否为正负号或数字 if not str or (not str[0].isdigit() and str[0] not in ['+', '-']): return 0 # 转换过程中如果遇到非数字字符,则停止转换 i = 1 while i < len(str) and str[i].isdigit(): i += 1 # 转换数字 num_str = str[:i] sign = -1 if num_str[0] == '-' else 1 num = 0 for c in num_str: if c.isdigit(): num = num * 10 + int(c) else: break # 判断转换后的数字是否超出了32位有符号整数的范围 max_int = 2**31 - 1 min_int = -2**31 num = num * sign if num > max_int: return max_int elif num < min_int: return min_int else: return num ``` 时间复杂度:$O(n)$,其中 $n$ 是字符串的长度。需要对字符串进行一次遍历。 空间复杂度:$O(1)$。除了常量空间之外,不需要额外的空间。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值