统计某类完全平方数 (20 分)
本题要求实现一个函数,判断任一给定整数N
是否满足条件:它是完全平方数,又至少有两位数字相同,如144、676等。
函数接口定义:
int IsTheNumber ( const int N );
其中N
是用户传入的参数。如果N
满足条件,则该函数必须返回1,否则返回0。
裁判测试程序样例:
#include <stdio.h>
#include <math.h>
int IsTheNumber ( const int N );
int main()
{
int n1, n2, i, cnt;
scanf("%d %d", &n1, &n2);
cnt = 0;
for ( i=n1; i<=n2; i++ ) {
if ( IsTheNumber(i) )
cnt++;
}
printf("cnt = %d\n", cnt);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
105 500
输出样例:
cnt = 6
分析:这道题让我很费解,题目呢也简单,但是应该是pintia上面有一点bug吧,我猜测的哈。本身我们的sqrt函数的参数是double类型的,但是在我使用sqrt(N)的时候竟然不会报错。因此我这里有两种答案。
代码实现:
int IsTheNumber ( const int N )
{
int a[10]={0};
for(int i=1;i<N/2;i++){
if(i*i==N){
int s=N;
while(s!=0){
int temp=s%10;
a[temp]++;
if(a[temp]==2)
return 1;
s=s/10;
}
}
}
return 0;
}
分析:这里我并没有sqrt函数,所以结果会耗时间一点。
代码实现:
int IsTheNumber ( const int N )
{
int n=(int)sqrt(N);
int a[10]={0};
if(n*n==N){
int s=N;
while(s){
int temp=s%10;
a[temp]++;
s /=10;
if(a[temp]==2)
return 1;
}
}
return 0;
}
分析:这里我就用到了sqrt函数,相比第一个代码节约了很多的时间,但是我就是很费解为什么会运行成功,但是在我们的编译软件是无法运行成功的。