先上题目(摘录)
Find and list all four-digit numbers in decimal notation that have the property that the sum of its four digits equals the sum of its digits when represented in hexadecimal (base 16) notation and also equals the sum of its digits when represented in duodecimal (base 12) notation.
就是找出十进制,十二进制,十六进制下各位和都相等的所有四位数(十进制下)
AC代码:
#include<iostream>
using namespace std;
int f(int num,int sys)//直接写一个进制转换函数
{
int x=0;
while(num)
{
x+=num%sys;
num/=sys;
}
return x;
}
int main()
{
for(int i=2992;i<10000;i++)
{
int res10,res12,res16;
res10=f(i,10);
res12=f(i,12);
res16=f(i,16);
if(res10==res12&&res12==res16)
cout<<i<<endl;
}
}
本题刚上手会有印象C++中有一个强制转换10进制成16进制的操作符(具体是啥写这篇时也还是不记得..)那么可不可以对于每一个四进制整数都先把它先转换成16进制,然后再把每位加起来,看看和一不一样?那么12进制又怎么办?
事实上本题只需要求每位的和,自己写一个很简单的如上算法就可以解决所有进制下的该类问题了。初学者可能并不是太注重进制直接的转换问题(除了要考试)但还是要关注一下的