首页 > 其他 > 详细

leetcode Reverse Integer

时间:2014-03-26 21:47:41      阅读:561      评论:0      收藏:0      [点我收藏+]

Reverse digits of an integer.

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

此题主要考查几种特殊的前导0的情况,还有单独为0的情况

注意利用c++中的reverse时要加命名空间,不然该函数会递归调用自己

bubuko.com,布布扣
#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;
}
bubuko.com,布布扣

leetcode Reverse Integer,布布扣,bubuko.com

leetcode Reverse Integer

原文:http://www.cnblogs.com/xiongqiangcs/p/3626267.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!