#include <vector>
#include <set>
#include<iostream>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
private:
int maxN;
public:
Solution(){}
Solution(int n):maxN(n){}
~Solution() {}
void findSymmetricSumOfSquares() {
for (int i = 1; i < maxN; i++) {
int sum = i * i;
if (isSymmetric(sum)) {
cout << i << " ";
}
}
//cout<<isSymmetricSum(1121)<<endl;
}
//法一,直接在数据上取出来前后数字
bool isSymmetricSum(int sum) {
bool is = true;
int maxWeight = 1;
while (sum / maxWeight > 10) maxWeight *= 10;
int highOrder=0, lowOrder=0;
while (sum!=0) {
highOrder = sum / maxWeight;
lowOrder = sum % 10;
if (highOrder != lowOrder) {
is = false;
break;
}
sum = sum % maxWeight;
sum /= 10;
maxWeight /= 100;
}
return is;
}
//法二,先将数据转化为字符串,然后首尾比较
bool isSymmetric(int x) {
bool isSym = true;
string xTostr = toString(x);
int strLength = xTostr.size();
for (int i = 0; i < strLength/2; i++) {
if (xTostr.at(i) != xTostr.at(strLength - i - 1)) {
isSym = false;
break;
}
}
return isSym;
}
string toString(int x) {
string intStr = "";
while (x) {
intStr += (x % 10 + '0');
x /= 10;
}
return intStr;
}
};
int main()
{
Solution test(256);
test.findSymmetricSumOfSquares();
system("pause");
return 0;
}
注意:
//严格的一个入口一个出口(return)
bool isSymmetric(int x) {
bool isSym = true;
string xTostr = toString(x);
int strLength = xTostr.size();
for (int i = 0; i < strLength/2; i++) {
if (xTostr.at(i) != xTostr.at(strLength - i - 1)) {
isSym = false;
break;
}
}
return isSym;
}
//试比较多个return,当代码比较复杂时,将产生阅读困难
bool isSymmetric(int x) {
string xTostr = toString(x);
int strLength = xTostr.size();
for (int i = 0; i < strLength/2; i++) {
if (xTostr.at(i) != xTostr.at(strLength - i - 1)) {
return false;
}
}
return true;
}