zoukankan      html  css  js  c++  java
  • Leetcode Reverse Integer

    Reverse digits of an integer.

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

    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.


    java code:

     1 /**
     2  max int is 2,147,483,647  Integer.MAX_VALUE Integer.MIN_VALUE
     3 * */
     4 public class ReverseInt {
     5     public static void main(String[] args) {
     6         int x = 1534236469;
     7         int y = reverse(x);
     8         System.out.println(y);
     9     }
    10 
    11     /*
    12     * runtime: 280ms
    13     * */
    14     public static int reverse(int x) {
    15         boolean isNeg = x < 0? true: false;
    16         long result = 0; // result might overflow
    17         int temp = Math.abs(x);
    18         if(temp == 0) {
    19             return 0;
    20         }
    21         while(temp > 0 ) {
    22             result = result * 10 + temp % 10 ;
    23             temp /=10;
    24         }
    25         if (result > Integer.MAX_VALUE) {return 0;}
    26         if(isNeg) {
    27             result *= -1;
    28         }
    29         return (int)result;
    30     }
    31 }

     Reference:

    1. http://fisherlei.blogspot.com/2012/12/leetcode-reverse-integer.html

  • 相关阅读:
    无向图求所有路径C#版
    centos 7 无痛安装 es
    rust 实现协程池
    spring boot fat jar 引入新的jar 文件到classpath
    nicolaka/netshoot 强大的容器网络问题解决工具
    使用nsenter 解决tcpcollect容器网络捕捉问题
    centraldogma git 镜像配置
    jmespath java 使用
    使用apicurio-registry 管理schema
    bfe 简单学习示例
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4790515.html
Copyright © 2011-2022 走看看