Reverse digits of an integer.
Example1: x = 123, return
321
Example2: x = -123, return -321
此题主要考查几种特殊的前导0的情况,还有单独为0的情况
注意利用c++中的reverse时要加命名空间,不然该函数会递归调用自己
#include <iostream> #include <cstdio> #include <sstream> #include <string> #include <cmath> using namespace std; int reverse(int x){ if (x == 0) return x; bool flag = (x > 0)? true : false; x = abs(x); stringstream ss; ss << x; string x_str; ss >>x_str; std::reverse(x_str.begin(),x_str.end()); string reverse_x = x_str.substr(x_str.find_first_not_of(‘0‘)); int res = atoi(reverse_x.c_str()); return flag ? res : (-res); } int main(){ cout<<reverse(123)<<endl; }
leetcode Reverse Integer,布布扣,bubuko.com
原文:http://www.cnblogs.com/xiongqiangcs/p/3626267.html