题目:

Reverse digits of an integer.

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

click to show spoilers.

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?

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.

代码:

class Solution {
public:
int reverse(int x) {
int v = x;
queue<int> que;
while ( true )
{
int digit = v % ;
que.push(digit);
v = v / ;
if ( abs(v)< ) break;
}
if ( v!=) que.push(v);
int ret = ;
while ( !que.empty() )
{
// cout << que.front() << endl;
if ( ret > INT_MAX/ || ret < INT_MIN/) return ; // overflow
ret = ret * + que.front();
que.pop();
}
return ret;
}
};

tips:

主要考虑出现overflow怎么处理,上述代码第一次写用了queue的结构,先进先出,方便调试各种case。

AC后对上述的代码进行了改进,改进结果如下,也可以AC。

class Solution {
public:
int reverse(int x) {
int ret = ;
while (x)
{
if ( ret > INT_MAX/ || ret < INT_MIN/ ) return ;
ret = ret* + x%;
x = x /;
}
return ret;
}
};

可以看到代码精炼了很多。另外判断是否越界不要直接比较 value>INT_MAX或者value<INT_MIN一般都是比较最大值除以10;因为value本身就越界了,再跟最大值比较也没有意义了。这是一个放缩的技巧。

=============================================

第二次过这道题,把corner case考虑完全了,就AC了。

class Solution {
public:
int reverse(int x) {
vector<int> digits;
int sign = x> ? : -;
int remain = ;
while ( remain> )
{
digits.push_back(fabs(x%));
x = x/;
remain = fabs(x);
}
int ret = ;
for ( int i=; i<digits.size(); ++i )
{
if ( INT_MAX/<ret || (INT_MAX/==ret && INT_MAX%<digits[i]) )
{
return ;
}
ret = ret* + digits[i];
}
return ret*sign;
}
};

最新文章

  1. 《使用Hibernate开发租房系统》内部测试笔试题
  2. 网络编程3-URL编程(URL)
  3. Git 版本管理
  4. Code Hunters: Hello, world!
  5. 2016 MIPT Pre-Finals Workshop Taiwan NTU Contest
  6. DevExpress 14.2 批量汉化 以及客户端的汉化
  7. Google Guava学习笔记——基础工具类Joiner的使用
  8. jquery1.8在ie8下not无效?
  9. K - Digital Roots(第二季水)
  10. AI 人工智能 探索 (二)
  11. 腾讯云数据库团队:SQL Server 数据加密功能解析
  12. MacBook 最近发现的一些问题和技巧
  13. Android预置Apk方法
  14. java集成memcached、redis防止缓存穿透
  15. SSL For Free 申请免费https SSL 凭证
  16. [Localization] R-CNN series for Localization and Detection
  17. 【Coursera】Technology :Fifth Week(2)
  18. Ubuntu16.04安装搜狗拼音输入法
  19. Linux RAID5+备份盘测试
  20. OSPF虚连接简单配置

热门文章

  1. Visual Studio 2010 vs2010 英文版 使用 已有的中文版 MSDN 帮助文档
  2. uvm_tlm——TLM1事务级建模方法(一)
  3. Hyper-V 2016 配置管理系列(部署篇)
  4. window下安装scala搭载Intellij IDE
  5. Copy Failed Error Access to fobidden
  6. 在SAP云平台的CloudFoundry环境下消费ABAP On-Premise OData服务
  7. TFS看板晨会
  8. HTTP 请求方法介绍
  9. GBDT回归的原理及Python实现
  10. PAT (Advanced Level) Practise - 1095. Cars on Campus (30)