• 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.


    其他人解法:https://leetcode.com/discuss/questions/oj/reverse-integer?sort=hot


     1 public class Solution 
     2 {
     3     // you need treat n as an unsigned value
     4     public static int reverse(int x) 
     5     {
     6         
     7         long y=0;
     8         int n=0;
     9         y=x;
    10         for(int i=0;i<31;i++)
    11         {
    12             if(y%10!=0)
    13                 n=i+1;
    14             y=y/10;    
    15         }
    16         y=0;
    17         for(int i=0;i<n;i++)
    18         {
    19                y=y*10;
    20             y=y+x%10;
    21             x=x/10;
    22         }
    23         int maxnum=(int) (Math.pow(2, 31)-1);
    24         int minnum=(int) (-Math.pow(2, 31));
    25 //        System.out.println(maxnum);
    26 //        System.out.println(minnum);
    27         if(y>maxnum||y<minnum)
    28             y=0;
    29         return (int)y;
    30     }
    31     public static void main(String args[])
    32     {
    33         System.out.println(reverse(1534236469));
    34     }
    35 }
  • 相关阅读:
    使用GitLab搭建Git仓库
    SpringBoot web开发
    springboot配置
    springboot自动配置原理
    springboot修改端口号
    springboot创建方式
    junit运行多个测试的方法
    junit常用注解
    junit断言
    sublime将.m文件关联MATLAB类型高亮
  • 原文地址:https://www.cnblogs.com/qq1029579233/p/4402718.html
Copyright © 2020-2023  润新知