# 6-7 統計某類完全平方數

6-7 統計某類完全平方數 (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
#define _CRT_SECURE_NO_WARNINGS
#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) {

	/*
		思路:
		  1.判斷完全平方數:
                    將sqrt(N)強轉爲int型,即n = (int)sqrt(N); 
                    如果最終n*n=N,則爲完全平方數,否則不是。
		  2.判斷是否至少兩個數相同:
                    類似基數排序的思想,設一個數組Array[10],數組下標代表0~9號桶;
                    將N的每一位數進行剝離,然後依次與0~9號桶標號對比,和哪個桶標號相同,哪個桶的數值就加一;
                    一旦有一個桶數值等於2,即至少有兩位數相同,滿足條件,return 1。
	*/

	int n = (int)sqrt(N);

	if (n*n == N) {

		int Array[10] = { 0 };
		int m = N;

		while (m > 0) {

			int tmp1 = m % 10;

			for (int i = 0; i < 10; i++) {
				if (tmp1 == i)
					Array[i]++;

				if (Array[i] == 2)
					return 1;
			}

			m = m / 10;

		}
		return 0;//如果m=0還沒有任意一個桶值爲2則不滿足條件
	}

	return 0;//任一條件不滿足,return 0
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章