LeetCode刷题笔记 [7] 整数反转
2019-02-24 16:52
281 查看
/* * @lc app=leetcode.cn id=7 lang=c * * [7] 整数反转 * * https://leetcode-cn.com/problems/reverse-integer/description/ * * algorithms * Easy (31.08%) * Total Accepted: 74K * Total Submissions: 238K * Testcase Example: '123' * * 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 * * 示例 1: * * 输入: 123 * 输出: 321 * * * 示例 2: * * 输入: -123 * 输出: -321 * * * 示例 3: * * 输入: 120 * 输出: 21 * * * 注意: * * 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。 * */ #include <stdio.h> #include <math.h> int reverse(int x) { int cmp,ori,rt=0,tmp[10]={0},i,j; for (i = 0; i < 10 && x != 0; i++) { tmp[i] = x % 10; x = x / 10; } for (j = 0; j < i;j++){ ori = rt; rt = 10 * rt + tmp[j]; cmp = rt / 10; if(ori!=cmp)//判断整形溢出 操作后除以10看和操作前是否相等 不相等就溢出了 return 0; } return rt; } /* int main(){ printf("%d", reverse(1534236469)); return 0; } */
这里判断整形数在操作后是否溢出用了一种比较颠覆我自己思路的方法,是知乎轮子哥提出的,即
判断整形变量是否溢出:操作后看和操作前是否相等 不相等就溢出了
学会之后觉得是很平常的方法,但是刚刚看到的时候确实是柳暗花明,可能这就是脑力的差距.
相关文章推荐
- leetcode的python实现 刷题笔记7: 反转整数
- [LeetCode-7] Reverse Integer(反转整数)
- Java&LeetCode 初入门——007. 整数反转
- Leetcode7.整数反转(python3)
- golang_算法: leetcode_字符串02-整数反转
- LeetCode:整数反转(Python版本)
- 【LeetCode】- Reverse Integer(将一个整数反转)
- leetcode_7. Reverse Integer 反转整数的各个数字
- LeetCode-Python-7. 整数反转
- LeetCode7——Reverse Integer(将一个整数反转,注意溢出的处理)
- leetcode-整数反转
- 【菜鸡的LeetCode答案】【C#】7.反转整数
- leetcode7. 整数反转
- leetcode 7.整数反转
- (LeetCode每日一刷02)反转整数
- LeetCode第七题--反转32位的整数
- [Leetcode] reverse integer 反转整数
- (LeetCode)反转整数
- LeetCode - 7. 反转整数
- Leetcode(C++)——7. 整数反转