zoukankan      html  css  js  c++  java
  • lintcode :reverse integer 颠倒整数

    题目:

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

    样例

    给定 x = 123,返回 321

    给定 x = -123,返回 -321

    解题:

    直接反转,越界处理好炒蛋

    Java程序:

    public class Solution {
        /**
         * @param n the integer to be reversed
         * @return the reversed integer
         */
        public int reverseInteger(int n) {
            // Write your code here
            int MAX = Integer.MAX_VALUE;
            if(n>=0){
                int res = 0;
                int num = n;
                while(n!=0){
                    if(res>MAX/10) return 0;
                    res =res *10 + n%10;
                    n = n/10;
                }
                return res;
            }else{
                int res = reverseInteger(-n);
                return -res;
            }
            
        }
    }
    View Code

    总耗时: 16030 ms

    Python程序:

     还没好,一直Pending,Python不需要处理越界问题,

    需要处理,上面说的是32位数,最大值是2的32次方,下面程序已经更改,可以AC

    class Solution:
        # @param {int} n the integer to be reversed
        # @return {int} the reversed integer
        def reverseInteger(self, n):
            # Write your code here
            MAX = 2147483647 
            flag = False
            if n<0:
                n = -n
                flag = True
            res = 0
            while n!=0:
                if res>MAX/10: return 0 
                res = res * 10 + n%10;
                n = n/10
            if flag:
                return -res
            else:
                return res
    View Code

    总耗时: 650 ms

  • 相关阅读:
    我用到的存储过程
    yii2图片处理扩展yii2-imagine的使用
    yii2——自定义widget
    YII2之 Scenario
    PHP获取某月天数
    docker版wordpress
    RBAC中 permission , role, rule 的理解
    mysql开启远程连接
    windows系统和ubuntu虚拟机之间文件共享——samba
    php生成随机字符串
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4890196.html
Copyright © 2011-2022 走看看