leetcode Reverse Integer
2015-11-03 22:03
323 查看
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
题目看起来很简单,但编写时候发现有些东西需要考虑清楚。
如处理当字符转换后的数是否溢出,以及当输入为-2147483648时,无法将其转换为正整数,因为其对应的正值在signed int类型中属于溢出。
为什么一定要把数字转换为字符串以后再进行逆序呢,这样不仅要消耗存储空间,还增加了运算负担。
优化后的代码如下:
如何进行优化才能走到最前面呢。。。
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
题目看起来很简单,但编写时候发现有些东西需要考虑清楚。
如处理当字符转换后的数是否溢出,以及当输入为-2147483648时,无法将其转换为正整数,因为其对应的正值在signed int类型中属于溢出。
class Solution { public: char* changeToChar(const int& x) { char *result; int len=0; int temp = x; while(temp != 0) { temp = temp/10; len++; } result = new char[len]; temp = x; int count = 0; while(temp != 0) { result[count] = '0' + temp%10; temp = temp/10; count++; } result[count] = '\0'; return result; } int changeToNum(char* data,const bool& pos) { long long num=0; int len = strlen(data); int count = 0; for(;count<len;count++) { num = num*10; num += data[count]-'0'; if((pos&&num > 0x7fffffff)||(!pos&&num>0x80000000)) return 0; } return num; } int reverse(int x) { int flag = -1,result=0; if(x == 0 || x == (signed int)0x80000000) return 0; bool pos = true; if(x<0) { pos = false; x= x*(-1); } char* temp = changeToChar(x); int len; len = strlen(temp); if(pos == true) return changeToNum(temp,pos); else return 0-(changeToNum(temp,pos)); } };
为什么一定要把数字转换为字符串以后再进行逆序呢,这样不仅要消耗存储空间,还增加了运算负担。
优化后的代码如下:
class Solution { public: int reverse(int x) { int ans=0,temp,indicator=1; if(x < 0) { indicator = -1; x = -x; } while(x > 0) { temp = ans*10 + x%10; if(temp/10 != ans) return 0; ans = temp; x = x/10; } return ans*indicator; } };
如何进行优化才能走到最前面呢。。。
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解