leetcode相关C++算法解答: https://github.com/Nereus-Minos/C_plus_plus-leetcode
题目:
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
实例:
123 得到-321
思路:
1.考虑溢出则其数值范围为 [-2^31, 2^31 - 1]。 if(ret<= (0-pow(2,31)) || ret >= (pow(2,31)-1)) return 0;
2.先得到整数的位数while((int)(x / pow(10 , weishu))) weishu++;
3.再根据位数得到值
代码:
class Solution {
public:
int reverse(int x) {
if(x<= (0-pow(2,31)) || x >= (pow(2,31)-1))
return 0;
int weishu = 1;
while((int)(x / pow(10 , weishu)))
{
weishu++;
}
int ret=0;
int temp;
for(int i = weishu-1, j=0; i>=0; i--,j++)
{
temp = (x / (pow(10 , i)));
ret += temp*(pow(10 , j));
x = x- temp*(pow(10 , i));
}
if(ret<= (0-pow(2,31)) || ret >= (pow(2,31)-1))
return 0;
return ret;
}
};
博客提供了 LeetCode 相关 C++ 算法解答,针对将 32 位有符号整数各位数字反转的题目,给出思路,先考虑溢出,数值范围为 [-2^31, 2^31 - 1],再得到整数位数并据此求值,还给出代码解答链接。
563

被折叠的 条评论
为什么被折叠?



