C++练习6:整数反转
题目
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。如果反转后整数超过 32 位的有符号整数的范围 [−2^31 , 2 ^31-1] ,就返回 0。假设环境不允许存储 64 位整数(有符号或无符号)。
示例 1:
输入:x = 123
输出:321
示例 2:
输入:x = -123
输出:-321
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
官方参考答案
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
};
作者:LeetCode
链接:https://leetcode-cn.com/problems/reverse-integer/solution/zheng-shu-fan-zhuan-by-leetcode/
方法1(取模运算法):
基本思路:核心为取出整数的“末尾数字”
链接: 取模运算思路.
#include<iostream>
using namespace std;
int main(){
int x, pop, rev = 0;
cout<<"请输入一个整数:"<<endl;
cin >> x;
while (x != 0) {
pop = x % 10;
x /= 10;
// cout<<pop<<endl;
rev = rev * 10 + pop;
}
cout<<"反转后的结果为:"<< rev <<endl;
}
方法2(字符串法):
基本思路:把整数变成字符串,再去反转这个字符串