LeetCode 7 Reverse Integer(翻转整数)

翻译

翻转一个整型数

例1:x = 123, 返回 321
例2:x = -123, 返回 -321

原文

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this? (来自LeetCode官网)

Here are some good questions to ask before coding. 
Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? 
ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? 
Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. 
How should you handle such cases?

For the purpose of this problem, 
assume that your function returns 0 when the reversed integer overflows.

Update (2014-11-10):

Test cases had been added to test the overflow behavior.

C#

public class Solution
{
    public int Reverse(int x)
    {
        try
        {
            string str = Math.Abs(x).ToString();
            string newStr = (x < 0) ? "-" : "";
            for (int i = str.Length - 1; i >= 0; i--)
            {
                newStr += str[i];
            }
            return int.Parse(newStr);
        }
        catch (Exception e)
        {
            return 0;
        }
    }
}

C++(来源于网络)

class Solution {
public:
    int reverse(int x) {
        int res = 0;
        while(x!=0){
            if(res>INT_MAX/10||res<INT_MIN/10){
                return 0;
            }
            res = res*10 + x%10;
            x = x/10;
        }
        return res;
    }
};
  • 2
    点赞
  • 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、付费专栏及课程。

余额充值