zoukankan      html  css  js  c++  java
  • 7_Reverse Integer

    7.Reverse Integer

    Given a 32-bit signed integer, reverse digits of an integer.

    Example 1:

    Input: 123
    Output: 321

    Example 2:

    Input: -123
    Output: -321

    Example 3:

    Input: 120
    Output: 21

    Note:
    Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    没有想出来, 仿照(或者照搬?)http://www.cnblogs.com/grandyang/p/4125588.html来写

    注意点:
    反转溢出问题, 解决方法: 使用比该数字范围大的类型定义返回值

    版本一: 拆分每个位的思想是我的, 其他细节参考上述博客

    class Solution {
    public:
        int reverse(int x) {
            long long res = 0;
            vector<int> bit;
            
            while (0 != x) {
                bit.push_back(x % 10);
                x /= 10;
            }
            
            for (int i = 0; i < bit.size(); i++) {
                res =res * 10 + bit[i];
            }
            
            return (res < INT_MIN || res > INT_MAX) ? 0 : res;
        }
    };
    

    版本二: 半个自己写的, 考虑符号, 虽然多余了

    class Solution {
    public:
        int reverse(int x) {
    		long long ret = 0;
    		// int positive = 1;
    		long long positive = 1;
    
    		if (x < 0) {
    			positive = -1;
    			x *= positive;
    		}
    
    		while (x != 0) {
    			ret = ret * 10 + x % 10;
    			x /= 10;
    		}
            
            ret *= positive;
    		
    		return (ret < INT_MIN || ret > INT_MAX) ? 0 : ret;
        }
    };
    
    class Solution {
    public:
        int reverse(int x) {
            long long int ret = 0;
            
            while(0 != x) {
                ret = ret*10 + x%10;
                x /= 10;
            }
            
            //return (ret > INT_MIN || ret < INT_MAX)? ret : 0;
             return (ret < INT_MIN || ret > INT_MAX) ? 0 : ret;
        }
    };
    
  • 相关阅读:
    JqGrid常用示例
    jqGrid无刷新分页,添加行按钮
    C#两个实体之间相同属性的映射
    Log4Net日志记录
    C#压缩图片
    ASP.Net MVC4.0+无刷新分页
    世界各个国家中英文sql建表
    ASP.NET多语言
    分布式事务处理中的幂等性
    分布式事务前瞻-接口幂等性
  • 原文地址:https://www.cnblogs.com/hesper/p/10397725.html
Copyright © 2011-2022 走看看