题目
要求实现一个函数,判断任一给定整数 N N N 是否满足条件:它是完全平方数,又至少有两位数字相同,如 144 、 676 144、676 144、676 等。
函数接口定义
int IsTheNumber ( const int N );
其中 N N N 是用户传入的参数。如果 N N N 满足条件,则该函数必须返回 1 1 1 ,否则返回 0 0 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
题解
解题思路
首先判断传进函数的数字是否是完全平方数,如果不是直接返回
0
0
0 ;如果是完全平方数则,创建一个数组用来判断
0
−
9
0-9
0−9 中的数字是否有重复的,并初始化为
0
0
0 ,用求模取余的方式来求出每一位的数字,进而判断该数字中是否有两个数字重复,如果没有返回
0
0
0 ,如果有则返回
1
1
1 即可。
完全平方数:完全平方指用一个整数乘以自己例如
1
∗
1
1*1
1∗1 ,
2
∗
2
2*2
2∗2 ,
3
∗
3
3*3
3∗3 等,依此类推。若一个数能表示成某个整数的平方的形式,则称这个数为完全平方数。完全平方数是非负数,而一个完全平方数的项有两个。
完整代码
#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;
}
/* 你的代码将被嵌在这里 */
int IsTheNumber(const int N)
{
int n = N, x, flag[10] = { 0 };
double root = sqrt(n);
if (root == (int)root) // 判断是否是完全平方数
{
while (n) // 判断是否有两个相同数字
{
x = n % 10;
n /= 10;
if (flag[x] == 1)
return 1;
flag[x] = 1;
}
return 0;
}
return 0;
}
AC代码
int IsTheNumber(const int N)
{
int n = N, x, flag[10] = { 0 };
double root = sqrt(n);
if (root == (int)root) //判断完全平方数
{
while (n)
{
x = n % 10;
n /= 10;
if (flag[x] == 1)
return 1;
else
flag[x] = 1;
}
return 0;
}
else
return 0;
}