问题
题目:[leetcode-9]
思路
回文的思路,但是关键是不许借助额外空间。
代码
其实这么做,不符合要求。但是也过了。
class Solution {
public:
bool isPalindrome(int x) {
std::stringstream ss;
ss << x;
std::string ret;
ss >> ret;
return std::equal( ret.begin(), ret.end(), ret.rbegin() );
}
};
代码1
本次的做法由于引入的额外变量是常数,所以并不影响。思路就是常规的解析。对于一个数字1234.分别从最高位和最低位进行解析。
- 计算数字位数
- 解析最高位和最低位
- 最高位:left = x / base_left % 10
- 最低位:right = x / base_right % 10
- 更新基数
- base_left /= 10
- base-right *= 10
比如1234,开始base_left = 1000, base_right = 1.left = 1, right 4.然后更新两侧的基数,base_left = 100, base_right = 10; left = 2, right = 3. 一次类推即可
/*
不让借助额外空间,那只能从高位和低位依次去比。
*/
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
else if( x < 10) return true;
else
{
// 首先获得数字位数
int tmp = x;
int n = 0;
while(tmp)
{
n++;
tmp /= 10;
}
// 解析最高位和最低位
int base_left = my_pow( 10, n-1 );
int base_right = 1;
for( int cnt = 0; cnt < n/2; ++cnt, base_left /= 10, base_right *= 10 )
{
int left = x / base_left % 10;
int right = x / base_right % 10;
if( left != right )
return false;
}
return true;
}
}
private:
int my_pow( int a, int b )
{
int ret = 1;
for( int i = 0; i < b; ++i )
{
ret *= a;
}
return ret;
}
};