本题要求实现一个函数,判断任一给定整数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 result = 0;
// 判断是否为完全平方数,且至少有两位数字相同
// 1.i从1开始n遍历,对于每一个i判断i*i是否等于N,若i如果是则返回1,如果不是则返回0
// 1.1用for循环判断
int num = 0;
int A[10] = {0};
int is_power = 0;
int i =1;
while(i <= N)
{
if(i * i == N )
{
num = N;
is_power = 1;
break;
}
else
{
i++;
}
}
int is_same = 0;
int n = 0;
int j = 0;
int count = 0;
if(is_power)
{
// 2.是否至少有两位数相同
// 2.1 将每一位拆解,进行比较
// 2.1.1 对10取余再除以10
while(num != 0)
{
A[j] = num % 10;
num = num / 10;
j++;
count++;
//n = i - 1;
}
/*
printf("A(N = %d):[ ", N);
for(int i = 0; i < 10; i++)
{
printf("%d ", A[i]);
}
printf("]");
printf(" %d\n", count);
*/
for(int j = 0; j < count - 1; j++)
{
for(int k = j + 1; k < count; k++)
{
if(A[j] == A[k])
{
is_same = 1;
break;
}
}
//如何两两比较
// for(int k = 1; (k < count) && (j != k); k++)
// {
// if(A[j] != A[k])
// {
// continue;
// }
// else
// {
// //printf("N=%d\n", N);
// is_same = 1;
// }
// }
}
// 2.2 用两个for循环进行两两比较
}
result = is_power & is_same;
return result;
}