数位枚举
abc
题目描述:设a、b、c均是0到9之间的数字,abc、bcc是两个三位数,且有:abc+bcc=532。求满足条件的所有a、b、c的值
方法一:
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 for(int a = 1; a <= 9; ++a) 7 { 8 for(int b = 1; b <= 9; ++b) 9 { 10 for(int c = 0; c <= 9; ++c) 11 { 12 int temp1 = a * 100 + b * 10 + c; 13 int temp2 = b * 100 + c * 11; 14 if(temp1 > 532)//一开始写的temp1 > 532 || temp2 > 532,导致无解,因为temp2不单调 15 return 0; 16 if(temp1 + temp2 == 532) 17 cout << a << " " << b << " " << c << endl; 18 } 19 } 20 } 21 }
方法二:
#include <iostream> using namespace std; int main() { for(int a = 0; a <= 9; ++a) { for(int b = 0; b <= 9; ++b) { for(int c = 0; c <= 9; ++c) { if(a * 100 + b * 110 + c * 12 == 532)//不要思维定势,可以直接加起来的 cout << a << " " << b << " " << c << endl; } } } }
反序数
题目描述:设N是一个四位数,它的9倍恰好是其反序数(例如:1234的反序数是4321)求N的值
#include <iostream> using namespace std; int rev(int x)//判断逆序或者回文的基本操作 { int res = 0; while(x) { res *= 10; res += x % 10; x /= 10; } return res; } int main() { for(int i = 1000; i <= 9999; ++i) { int temp = rev(i); if(temp == i * 9) cout << i << endl; } }
这题固然可以按数位进行手动计算,但利用判逆序的方法更简洁
这种题可以枚举每一位数,也可以直接按数的大小枚举,两种方法都要灵活应用,不要思维定势吊死在一种方法上

浙公网安备 33010602011771号