leetcode->Reverse Integer
来源:互联网 发布:武汉软件新城 编辑:程序博客网 时间:2024/06/08 03:07
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package Reverse;/** * * @author suisuihan */public class Resverse { public int reverse(int x) { int ret = 0; String temp = null; if(x >= 0){ temp = String.valueOf(x); }else{ temp = String.valueOf(Math.abs(x)); } StringBuffer buf = new StringBuffer(temp); temp = buf.reverse().toString(); if(x >=0){ try { ret = Integer.valueOf(temp); } catch (Exception e) { if(e.toString().contains("NumberFormatException")){ ret = 0; } }finally{ return ret; } }else{ try { ret = 0 - Integer.valueOf(temp); } catch (Exception e) { if(e.toString().contains("NumberFormatException")){ ret = 0; } }finally{ return ret; } } } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int x = 987654321; Resverse test = new Resverse(); System.out.println(test.reverse(x)); }}
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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.
1、思路:不知道算不算取巧,思路是直接将int转换为string,利用stringbuffer的reverse功能。
2、使用时在想如果越界了怎么办,结果抛出java.lang.NumberFormatException: For input string: "987654321"异常。catch之后搞定。
- LeetCode:Reverse Integer
- LeetCode: Reverse Integer
- [Leetcode] Reverse Integer
- LeetCode : Reverse Integer
- [LeetCode] Reverse Integer
- Leetcode: Reverse Integer
- LeetCode 7 - Reverse Integer
- leetcode 104: Reverse Integer
- Leetcode : Reverse Integer
- 【leetcode】Reverse Integer
- [LeetCode]Reverse Integer
- LeetCode-Reverse Integer
- [leetcode] Reverse Integer
- LeetCode - Reverse Integer
- leetcode之Reverse Integer
- LeetCode | Reverse Integer
- LeetCode: Reverse Integer
- Leetcode: Reverse Integer
- 注册表模式
- C++的四种强制转换
- 成为一名android系统工程师——工作伊始
- ASP.NET生成验证码
- 解决SQL Server 2005数据库中datetime时间字段在前端显示时分秒的问题
- leetcode->Reverse Integer
- 《C#高级教程》学习笔记7
- Linux 内核加载过程
- 解决织梦中栏目的图片路径问题
- 防止.class被反编译 的方法
- 从五子棋来看OOP编程思想
- Unreal Engine 4 C++ 隐藏系统光标
- linux 网络流量监控工具iftop
- hook技术