判断任一给定整数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
答案:该答案由网上学来,最初的解题思路是使用指针(或者转成字符串),取每一位进行循环判断,太麻烦。
int IsTheNumber ( const int N )
{
int n=N, tem, i;
if( sqrt(n)==(int)sqrt(n) )
{
int num[10]={0}; //定义数组长度为10,不是因为传入数字位数为10,而是因为每位数字可能为0-9
while( n>0 ) 遍历N的每一位上的数字,在相应的数组中自加 如果有一个数组元素等于2 说明至少有2个位上的数相同
{
tem=n%10;
for( i=0; i<=9; i++ )
{
if( tem==i )
{
num[i]++;
if( num[i]==2 )
return 1;
}
}
n=n/10;
}
return 0;
}
else
return 0;
}
需要注意return的位置以及数组的用法。