zoukankan      html  css  js  c++  java
  • Reverse Integer

    原题目   https://leetcode.com/problems/reverse-integer/

    Reverse digits of an integer.

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

    click to show spoilers.

    Have you thought about this?

    Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

    If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

    Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

    For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    Update (2014-11-10):
    Test cases had been added to test the overflow behavior.

    题目大意,反转int数字

    #include <iostream>
    using namespace std;
    
    
    //反转int (利用了long long)
    int reverse(int x) {
        long long s = 0;         
        while (x != 0) {
            s = s * 10 + x %10;
            x = x / 10;
        }
        if (s > INT_MAX || s < INT_MIN)
            return 0;
        return s;
    }
    
    //反正int (没有使用long long)
    int reverse(int x){
        int s = 0;
        while(x != 0) {
            // s * 10 大于Int_Max 或者 s * 10 + x % 10 大于Int_Max
            if (x > 0 && (s > INT_MAX / 10 || (s == INT_MAX / 10 && x % 10 > INT_MAX % 10))) 
                return 0;
            if (x < 0 && (s < INT_MIN / 10 || (s == INT_MIN / 10 && x % 10 < INT_MIN % 10))) 
                return 0;
            s = s * 10 + x % 10;
            x /= 10;
        }
        return s;
    }
    
    void test(){
        int x = 4568412;
        // x = -4568412;
        // x = 1000;
        // x = -1000;
        // x = 0;
        // x = INT_MAX + 1;
        // x = INT_MIN - 1;
        reverse(x);
    }
    
    int main()
    {
        
        test();
    
        system("pause");
        return 0;
    }
  • 相关阅读:
    pdf.js-----后端返回utf-8数据流,前端处理数据展示pdf
    正则表达式之去除前后空格
    ng之邮箱校验
    ng-校验重复并提示具体重复内容
    input 数值框处理
    逻辑之不重复
    ng -----监听变化($scope.$watch())
    js中document的用法
    php中12个魔术方法
    php 中const和 define的区别
  • 原文地址:https://www.cnblogs.com/the-game-over/p/4704931.html
Copyright © 2011-2022 走看看