zoukankan      html  css  js  c++  java
  • [Leetcode 14] 7 Reverse Integer

    Problem:

    Reverse digits of an integer.

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

    Analysis:

    It's the basic conversion problem. The only thing to note is that keep the negative number as negative and positive as positive.

    Code:

    View Code
     1 public class Solution {
     2     public int reverse(int x) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int rx = 0;
     6         boolean isNegative = (x<0)? true : false;
     7         
     8         if (isNegative)
     9             x = -x;
    10         
    11                 
    12         while (x > 0) {
    13             rx = rx*10 + x%10;
    14             x /= 10;
    15         }
    16         
    17         return isNegative? -rx : rx;
    18     }
    19 }

    Here is a simplified version of the code

    View Code
     1 public class Solution {
     2     public int reverse(int x) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int res = 0;
     6         
     7         while (x != 0) {
     8             res = res * 10 + x % 10;
     9             x /= 10;
    10         }
    11         
    12         return res;
    13     }
    14 }

    Attention:

    As the Spoiled Information mentioned, there are many problems to consider before starting to code.

    The first thing is how to deal with negative numbers?

    The second thing is how to deal with numbers ending with 0, e.g. 10, 100, 1000, should the reversed number be 01 or 1?

    Finally, the biggest problem is overflow after reversing, example is that for a signed 32bit integer 1000000003, the reversed integer is 3000000001, which exceeds the maximum value of signed 32-bit integer - 2147483647. One possible way to handle it is adding a isValid flag to notify user whether the returned result is valid

  • 相关阅读:
    ORM执行原生sql, Python脚本调用Django环境, ORM事务, sql模式说明
    ORM多表更新删除 查询
    ORM多表操作
    Java BigDecimal类型的数据运算方法
    js获取表格中的数据转化为json字符串
    在threamleaf中使用循环遍历输出list集合
    sql中使用cast转化数据格式(整数或者小数)
    mybatis的xml中使用模糊搜索查询
    k8s挂载ceph
    kubernetes HPA
  • 原文地址:https://www.cnblogs.com/freeneng/p/3014553.html
Copyright © 2011-2022 走看看