求一个整数的长度:
int getLen(int x)
{
int len = 0, t = x;
while (t)
{
t = t / 10;
len += 1;
}
return len;
}
题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
代码:
class Solution {
public:
int reverse(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int flag=true;
if(x<0)
{
flag=false;
x=-x;
}
int len = getLen(x);
int rst = 0;
for (int i = 1; i <= len; i++)
{
int t = x % 10;
x = x / 10;
int a = len - i, temp = 1;
while (a > 0)
{
temp = temp * 10;
a--;
}
rst += t * temp;
}
if(flag) return rst;
else return -rst;
}
int getLen(int x)
{
int len = 0, t = x;
while (t)
{
t = t / 10;
len += 1;
}
return len;
}
};