LeetCode之7_Reverse Integer

来源:互联网 发布:python入门经典pdf下载 编辑:程序博客网 时间:2024/06/06 11:39

题目原文:

 

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;}};


 

 

1 0
原创粉丝点击