码迷,mamicode.com
首页 > 其他好文 > 详细

413 反转整数

时间:2018-06-24 16:56:57      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:.com   turn   lintcode   csdn   超出   get   des   参考   问题   

原题网址:https://www.lintcode.com/problem/reverse-integer/description

描述

将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。

您在真实的面试中是否遇到过这个题?  

样例

给定 x = 123,返回 321

给定 x = -123,返回 -321

标签
整数
 
思路:按位依次取出数字存入数组,再将数字取出乘以对应的权值完成反转。注意反转过程中随时判断数值是否超出int型范围,超出范围则返回0。
 
AC代码:
class Solution {
public:
    /**
     * @param n: the integer to be reversed
     * @return: the reversed integer
     */
    int reverseInteger(int n) {
        // write your code here

int m=n,result=0; vector<int> tmp; while(m) { tmp.push_back(m%10); m=m/10; } int size=tmp.size(); for (int i=0;i<size;i++) { result=result+tmp[i]*pow(10.0,size-1-i); if (result>=INT_MAX||result<=INT_MIN) { return 0; } } return result; } };

 

其他思路:

https://blog.csdn.net/zsjmfy/article/details/53405494

https://www.cnblogs.com/grandyang/p/5778281.html   代码精简

https://blog.csdn.net/qq_23225317/article/details/53641864

 

 

413 反转整数

标签:.com   turn   lintcode   csdn   超出   get   des   参考   问题   

原文地址:https://www.cnblogs.com/Tang-tangt/p/9220772.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!