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

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

    给定一个32位有符号整数,将整数的每位反转,如下:

    Example 1:

    Input: 123
    Output:  321

    Example 2:

    Input: -123
    Output: -321 

    Example 3:

    Input: 120
    Output: 21

    注意:
    假设翻转后超出32位有符号数的范围(溢出),那么返回0.

    大神代码bitzhuwei

    public int reverse(int x)
    {
        int result = 0;
    
        while (x != 0)
        {
            int tail = x % 10;
            int newResult = result * 10 + tail;
            if ((newResult - tail) / 10 != result)
            { return 0; }
            result = newResult;
            x = x / 10;
        }
    
        return result;
    }

    我的代码(主要难点在于溢出的判定)

    class Solution {
    public int reverse(int x) {
    int result=0;
    double temp=0;
    int sum=0;
    int length=String.valueOf(x).length();

    if (x<0)
    length=length-2;
    else
    length=length-1;

    while(x/10!=0) {
    temp=(x%10)*(Math.pow(10, length));
    sum=(int) (temp+result);
    if(Math.abs(temp)>Math.abs(sum)-Math.abs(result))
    return 0;
    result+=temp;
    x/=10;
    length--;
    }

    sum=result+x;
    if(Math.abs(x)>Math.abs(sum)-Math.abs(result))
    return 0;
    result+=x;
    return result;
    }
    }

     
  • 相关阅读:
    线程安全好文章
    分布式事务
    jvm内存泄漏问题分析过程
    Java8--Lambda表达式
    ZK Watcher 的原理和实现
    JVM垃圾回收算法
    linux常用命令
    Excel常用函数汇总
    Debian 镜像使用帮助
    photon 下载地址
  • 原文地址:https://www.cnblogs.com/mafang/p/8470871.html
Copyright © 2011-2022 走看看