zoukankan      html  css  js  c++  java
  • Leetcode: 7. Reverse Integer

    Description

    Reverse digits of an integer.

    Example

    Example1: x = 123, return 321
    Example2: x = -123, return -321
    
    Note:
    The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
    
    Subscribe to see which companies asked this question.
    

    思路

    • 这个题好像也没有什么简便方法,注意边界条件吧

    代码

    • 时间复杂度:O(m) m为输入数的有多少位
    class Solution {
    public:
        const int max_int = 2147483647;
        const int min_int = -2147483648;
        
        int reverse(int x) {
            if(x >= -9 && x <= 9) return x;
            if(x == min_int || x == max_int) return 0;
            
            vector<int> num(10, 0);
            bool isNeg = false;
            long long sum = 0;
            int count = 0;
            
            if(x < 0){
                x = -x;
                isNeg = true;
            }
            
            while(x){
                num[count++] = x % 10;
                x /= 10;
            }
            
            for(int i = 0; i < count; i++)
                sum = sum * 10 + num[i];
                
            if(sum > max_int){
                if(isNeg && -sum == min_int) return min_int;
                return 0;
            }
            
            return isNeg ? -sum : sum;
        }
    };
    
  • 相关阅读:
    11、angular 的依赖注入
    gulp插件列表
    gulp 列表
    gulp 教程
    html5模板
    yeoman官网
    node.js 增删改查(原始)
    配置MongoDB
    MongoDB手稿
    node.js 手稿
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6810016.html
Copyright © 2011-2022 走看看