Chinaunix首页 | 论坛 | 博客
  • 博客访问: 341194
  • 博文数量: 329
  • 博客积分: 2633
  • 博客等级: 少校
  • 技术积分: 3633
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-22 15:43
文章分类

全部博文(329)

文章存档

2013年(244)

2012年(46)

2011年(39)

我的朋友

分类: Java

2013-10-19 19:19:34


Reverse digits of an integer.

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

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).

其实就是数字逆序,但是要注意正数负数,求mod即可

点击(此处)折叠或打开

  1. public class Solution {
  2.     public int reverse(int x) {
  3.         // Note: The Solution object is instantiated only once and is reused by each test case.
  4.         int ans = 0;
  5.         while (x != 0) {
  6.             ans = ans * 10 + x % 10;
  7.             x /= 10;
  8.         }
  9.         return ans;
  10.     }
  11. }



阅读(737) | 评论(0) | 转发(0) |
0

上一篇:构造函数的初始化列表

下一篇:没有了

给主人留下些什么吧!~~