【leetcode-7】Reverse Integer(C语言)
2015-07-11 08:43
567 查看
问题描述:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
这道题比较讨厌的地方在于如何判断溢出,好吧,我的方法比较low,因为我只会比较+法的溢出,,但是效果还不错,运行时间是4ms
看了博客之后发现这种判断溢出的方法很不错。改之,但是时间居然会达到8ms。
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
这道题比较讨厌的地方在于如何判断溢出,好吧,我的方法比较low,因为我只会比较+法的溢出,,但是效果还不错,运行时间是4ms
[code]int reverse(int x) { bool negative = false; if(x<0){ negative = true; x = -x; } int nums = 0; int tmpNum; int tmp; int i; while(x){ tmpNum = nums; tmp = 0; for(i = 0;i<10;i++){ tmp = tmp+tmpNum; if(tmp<tmpNum) return 0; } nums = tmp; nums=nums+x%10; x = x/10; } if(negative) return -1*nums; return nums; }
看了博客之后发现这种判断溢出的方法很不错。改之,但是时间居然会达到8ms。
[code]int reverse(int x) { bool negative = false; if(x<0){ negative = true; x = -x; } int nums = 0; int tmpNum; int tmp; int i; while(x){ if(nums>(INT_MAX-x%10)/10)//成立,则一定会超 return 0; nums=nums*10+x%10; x = x/10; } if(negative) return -nums; return nums; }
相关文章推荐
- 使用#ifdef _cplusplus 实现c 和 c++的混合编程
- uplooking-C语言基础
- 不可以!
- C小加 之 随机数
- 黑马程序员-IOS学习笔记 C语言编程时常犯十八个错误
- c语言学习之数组3
- c语言学习之数组2
- c语言学习之数组2
- [强制类型转换]C语言中的强制类型转换相关
- 初识C++
- c语言学习之数组
- [memory]C++中栈区 堆区 常量区(由一道面试题目而学习)
- [Pointer]在C语言中进行float型与uint8型数组内存拷贝时出现的问题与解决
- [HWRelated]C语言中的底层技术
- [Pointer]C语言中指针的高级用法
- [List]C语言实现链表
- [Memory]C语言中的内存分配
- [enum]C语言中的枚举
- [PreProccess]C语言中预处理指令的使用
- [string]C语言中字符串使用需注意的地方