zoukankan      html  css  js  c++  java
  • leetcode Reverse Integer

    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;
    }
  • 相关阅读:
    POJ
    CodeForces
    部分和问题
    NOIP200502校门外的树
    消灭虫子
    抓牛
    最长不下降子序列的长度
    HDNoip201501计算结果最小
    抽签
    Ants
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3626267.html
Copyright © 2011-2022 走看看