鱼C论坛

 找回密码
 立即注册
查看: 1254|回复: 0

[学习笔记] leetcode 7. Reverse Integer

[复制链接]
发表于 2019-8-28 05:59:52 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

  2. Example 1:

  3. Input: 123
  4. Output: 321
  5. Example 2:

  6. Input: -123
  7. Output: -321
  8. Example 3:

  9. Input: 120
  10. Output: 21
  11. Note:
  12. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
复制代码


First try

  1. import java.math.BigInteger;

  2. class Solution {
  3.     public int reverse(int x) {
  4.         String num = Integer.toString(x);
  5.         
  6.         String result = "";
  7.         
  8.         int len = num.length();
  9.         
  10.         int flag = 0;
  11.         
  12.         if(num.substring(0,1).equals("-")){
  13.             
  14.             flag = 1;
  15.             
  16.             num = num.substring(1,len);
  17.             
  18.             len = len -1;
  19.             
  20.         }
  21.         
  22.         for(int i = 0 ; i< len; i++){
  23.             
  24.             result = num.substring(i,i+1) + result;
  25.         }
  26.         
  27.         BigInteger n = new BigInteger(result);
  28.         
  29.         BigInteger s = new BigInteger("-2147483648");
  30.         BigInteger b = new BigInteger("2147483647");
  31.         
  32.         if(n.compareTo(s)<0  || n.compareTo(b)>0){
  33.             
  34.             return 0;
  35.         }
  36.         
  37.         x = Integer.parseInt(result);
  38.         
  39.         if(flag == 1){
  40.             
  41.             return 0-x;
  42.         }
  43.         else{
  44.             
  45.             return x;
  46.         }
  47.     }
  48. }
复制代码


Second try.

  1. class Solution {
  2.     public int reverse(int x) {
  3.         
  4.         long result = 0;
  5.         
  6.         while(x != 0){
  7.             
  8.             result = result * 10 + x % 10;
  9.             
  10.             x = x/10;
  11.         }
  12.         
  13.         if(result > 2147483647 || result < -2147483648  )
  14.             return 0;
  15.         
  16.         return (int)result;
  17.         
  18. }
  19. }
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 13:53

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表