*Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
思路:如果是一个正数,不断的取÷10的余数再10,再加上新的余数。
比如:123,
第一次123%10=3,然后123÷10=12
第二次12%10=2,然后12÷10=1
第三次1%10=1,然后1÷10=0 ,等于0停止循环
这样从上到下我们就得到了3,2,1
想要得到321则需要3100+210+1,即在得到下一个余数的同时给上一个余数10。
/*Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321 */
#include<iostream>
using namespace std;
long reverse(int x){
int symbol=1; //符号,位数
long remainder=0,num=0;
if(x<0) {
symbol =- 1; //记录符号
x =- x;}
while(x!=0)
{
remainder = x%10;
x /= 10;
num = num*10 + remainder;
}
return symbol*num;
}
int main()
{
cout<<reverse(15472319);
return 0;
}

该博客介绍了如何使用C++解决LeetCode上的问题——反转32位整数。通过不断取整数除以10的余数并累积,可以得到整数的翻转值。例如,对于输入123,其翻转过程为123→3→12→1,最终得到321,实现方式是在每次得到新余数时将它加到上一次的10倍上。
787

被折叠的 条评论
为什么被折叠?



