LeetCode(7): 整数反转

题目:
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

输入: 123
输出: 321
示例 2:

输入: -123
输出: -321
示例 3:

输入: 120
输出: 21
注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

来源:力扣(LeetCode)


c++ac代码:

class Solution {
public:
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>
#include <limits.h>
void swap_char(char *a, char *b)
{
    char t = *a;
    *a = *b;
    *b = t;
}
void reverse_str(char *s)
{
    if(s[0] == '-')
    {
        reverse_str(s+1);
        return;
    }
    int len = strlen(s);
    for(int i=0;i<len/2;i++)
        swap_char(&s[i], &s[len-1-i]);
}
int reverse(int x){
    char buf[30];
    sprintf(buf,"%d", x);
    reverse_str(buf);
    int64_t num64;
    sscanf(buf,"%"SCNd64"", &num64);
    if(num64>INT_MAX || num64 < INT_MIN)
        return 0;
    return (int)num64;
}
};
发布了111 篇原创文章 · 获赞 13 · 访问量 3129

猜你喜欢

转载自blog.csdn.net/wx_assa/article/details/103484933