Reverse Integer
2015-06-23 21:06
204 查看
1. Question
反转一个整数的数位(注意溢出情况)Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321
2. Solution
2.1 整除取余法
//可以直接用String的reverse方法,但是效率低 public class Solution { public int reverse( int x ){ String orig = String.valueOf(Math.abs(x)); StringBuilder res = new StringBuilder(); if( x<0 ) res.append('-'); for( int i=orig.length()-1; i>=0 ; i-- ) res.append( orig.charAt(i) ); try{ x = Integer.parseInt(res.toString()); }catch( NumberFormatException e ){ x = 0; } return x; } }
View Code
3. 复杂度分析
O(n)相关文章推荐
- Lua利用元表实现修饰器
- 黑马程序员--字典转模型
- Android开发:GridView与ListView相互切换(动画效果)
- 重新开始拾起我的安卓之路,什么时候开始都不算晚!!!!
- 黑马程序员--搭建界面,九宫格
- class struct关键字区别
- 四年下学期古诗
- 黑马程序员--完整的设计一个动画从开始到退出
- python定时器爬取豆瓣音乐Top榜歌名
- Android中Fragment的知识
- 黑马程序员--NSArray,NSString,NSSet,NSDictionary,NSNumber,NSValue 及其可变(NSMutable..)
- LeetCode 101 Symmetric Tree
- onCreate()方法中获取View的宽高
- Swift语言学习(三)基础操作符
- python定时器爬取豆瓣音乐Top榜歌名
- C# this.Hide()
- 数据源,动态代理
- 各种编码UNICODE、UTF-8、ANSI、ASCII、GB2312、GBK详解
- 单一职责原则-和-开放-封闭原则-和-依赖倒转原则
- 计算机视觉进展二十年 (1995~2015)