zoukankan      html  css  js  c++  java
  • leetcode : 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.

    Subscribe to see which companies asked this question

    byte的取值范围为-128~127,占用1个字节(-2的7次方到2的7次方-1)
    short的取值范围为-32768~32767,占用2个字节(-2的15次方到2的15次方-1)
    int的取值范围为(-2147483648~2147483647),占用4个字节(-2的31次方到2的31次方-1)
    long的取值范围为(-9223372036854774808~9223372036854774807),占用8个字节(-2的63次方到2的63次方-1)
     
    转:
    (1) 取模的方式,逐个从右往左reverse。
    (2)防止溢出,用float先保存。
     
    public class Solution {
        public int reverse(int x) {
             
             long rev = 0;
             while(x != 0) {
                 rev = rev * 10 + x % 10;
                 x = x / 10;
                 if(rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) {
                     return 0;
                 }
             }
             return (int) rev;
        }
    }
    

      

     
  • 相关阅读:
    jquery笔记
    linux的日常经常使用的命令
    IDEA设置类注解和方法注解(详解)
    java读取项目或包下面的属性文件方法
    枚举类的使用
    将一个浮点数转化为人民币大写字符串
    简单五子棋实现
    crontab 设置服务器定期执行备份工作
    linux创建日期文件名
    代码层读写分离实现
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6361868.html
Copyright © 2011-2022 走看看