9. 回文数
1. 基础:C++中数字与字符串相互转换
1.1 数字转换字符串
1.1.1 方法一(利用的stringstream,可以是浮点数)
库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。
1.stringstream::str(); returns a string object with a copy of the current contents of the stream.
2.stringstream::str (const string& s); sets s as the contents of the stream, discarding any previous contents.
3.stringstream清空,stringstream s; s.str("");
4.实现任意类型的转换
template<typename out_type, typename in_value>
out_type convert(const in_value & t){
stringstream stream;
stream<<t;//向流中传值
out_type result;//这里存储转换结果
stream>>result;//向result中写入值
return result;
}
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
double x;
string str;//这里存储转换结果
stringstream ss;
cin >> x;
ss << x;//向流中传值
ss >> str;//向result中写入值
cout << str;
return 0;
}
1.1.2.方法二(利用中的to_string()方法,浮点数会附带小数点后六位,不足补零,不推荐浮点数使用)
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
double x;
string str;
cin >> x;
str = to_string(x);
cout << str;
return 0;
}
1.2 字符串转换为数字
1.2.1 方法一(利用的stringstream,可以是浮点数)
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
double x;
string str;
stringstream ss;
cin >> str;
ss << str;
ss >> x;
cout << x;
return 0;
}
1.2.2 方法二(利用中的stoi()函数,其中还有对于其他类型的函数,如stod(),stof()等,根据类型选取)
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x;
string str;
cin >> str;
x = stoi(str);
cout << x;
return 0;
}
2. 回文数字判断解法
2.1 转换字符串
class Solution
{
public:
bool isPalindrome(int x)
{
bool result;
if (x < 0)
{
return false;
}
stringstream ss;
string str, reversedStr;
ss << x;
ss >> str;
int strSize = int(str.size());
for (int index = strSize - 1; index >= 0; index--)
{
reversedStr.push_back(str[index]);
}
result = str == reversedStr;
return result;
}
};
类似解法:
class Solution {
public:
//to_string 将数字转换字符串
bool isPalindrome(int x) {
bool result;
if(x<0) return false;
string s,s_reverse;
//s=to_string(x);
stringstream ss;
ss << x;//向流中传值
ss >> s;//向result中写入值
int size=s.size();
for(int index=size-1;index>=0;index--){
s_reverse.push_back(s[index]);
}
// if (s.compare(s_reverse) != 0)
// return false;
// return true;
result = s == s_reverse;
return result;
}
};
2.2 数学方法
reverseNumber = reverseNumber * 10 + x % 10;//从右往左得到的数字
x = x / 10;//减去reverseNumber位数从左往右剩余数字
{
public:
bool isPalindrome(int x)
{
bool result;
//避免例如x = 110的情况
if (x < 0 || (x != 0 && x % 10 == 0))
{
return false;
}
int reverseNumber = 0;
//考虑一下为什么x = 21时,不会出错
while (x > reverseNumber)//减少判断次数,时间复杂度:O(log n),对于每次迭代,我们会将输入除以 10,因此时间复杂O(logn)
{
reverseNumber = reverseNumber * 10 + x % 10;//从右往左得到的数字
x = x / 10;//减去reverseNumber位数从左往右剩余数字
}
//分别是偶数位和奇数位的情况
result = (x == reverseNumber) || (x == reverseNumber / 10);
return result;
}
};
类似方法:
{
public:
bool isPalindrome(int x)
{
long y = 0, z = x;
while ( z > 0 ) {
y = 10 * y + (z % 10);
z /= 10;
}
return (x-y) == 0;
}
};