您的位置:首页 > 编程语言 > C语言/C++

LeetCode之7_Reverse Integer

2016-04-04 19:02 471 查看
题目原文:

 

Reverse digits of an integer.

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

click to show spoilers.

Subscribe to see which companies asked this question

 

分析:将整数倒序,符号不变,需要注意的是当改变后的值超出整数的可表示范围后,返回0.

 

代码:

 

//Reverse digits of an integer.
//
//Example1: x = 123, return 321
//Example2: x = -123, return -321

#include <iostream>
using namespace std;

class Solution {
public:
int reverse(int x) {
int nFlag = 1;
int nRet = 0;
int nLeft =0;
int nOld = 0;

if (x < 0)
{
x *= -1;
nFlag = -1;
}
while (x != 0)
{
nLeft = x % 10;
x = x/10;
nOld = nRet;
nRet = nRet *10 + nLeft;
}

if (nOld  != nRet / 10)
{
return 0;
}

nRet *= nFlag;
return nRet;
}
};


 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode