博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode--Reverse Integer
阅读量:4517 次
发布时间:2019-06-08

本文共 2053 字,大约阅读时间需要 6 分钟。

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -32

思路:

  很简单的思路,对x对10取余数,把x从低位到高位的数字依次提取出来,再每次对结果乘10加上新取出的个位,最后x=x/10,循环到x为0为止。

public class Solution {    public int reverse(int x) {        int result = 0;        while(x!=0){            result = result*10+x%10;            x /=10;        }        return result;            }}

 Spoiler:

  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?

  Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

  spoiler指出了要考虑溢出的情况,32位有符号整数的取值范围是-2147483648~2147483647,一共2^32次方个,从新写了个带判断溢出的结果,判断依据是正数加正数如果为负数了则是溢出,负数加负数为正数了也是溢出。

package com.bupt.tools;import java.util.Scanner;public class Test {        private static boolean flag;        public static int reverseint(int x){        flag = false;        int sign=x>0?1:-1;        int result = 0;        while(x!=0){            result = result*10+x%10;            x/=10;        }        if(sign==1){            if(result<0){                flag = true;                return -1;            }        }        else if(sign==-1){            if(result>0){                flag = true;                return -1;            }                }        return result;    }        public static void main(String[] args){        Scanner sc = new Scanner(System.in);                while(sc.hasNext()){            int result = Test.reverseint(sc.nextInt());            if(!Test.flag)                System.out.println(result);            else                System.out.println("Overflow!");         }        sc.close();            }}

 

转载于:https://www.cnblogs.com/zhoujunfu/p/4041846.html

你可能感兴趣的文章
单词计数问题
查看>>
php 魔术方法 __autoload()
查看>>
js div拖动动画运行轨迹效果
查看>>
Recipe 1.9. Processing a String One Word at a Time
查看>>
Linux 下查看系统是32位 还是64 位的方法
查看>>
MySQL 引擎 和 InnoDB并发控制 简介
查看>>
Dave Python 练习二
查看>>
.net知识体系
查看>>
第二章 第五节 获取帮助
查看>>
关于源代码及其管理工具的总结
查看>>
此文对你人生会有莫大好处的,建议永久保存 2013-07-26 11:04 476人阅读 评论(0) ...
查看>>
JQuery怎样返回前一页
查看>>
Best Time to Buy and Sell Stock
查看>>
Web服务器的原理
查看>>
记录ok6410 jlink 命令行调试uboot
查看>>
ASP.net 内置对象
查看>>
QT使用mysql
查看>>
判断有无网
查看>>
ASP.NET简介
查看>>
php开发环境搭建
查看>>