解题思路

题目要求将整数按照其数位的整除性质分为三类:

  1. H(Happy):数字可以被部分包含的数位整除
  2. S(Sad):数字不能被任何包含的数位整除
  3. G(Great):数字可以被所有包含的数位整除

解题思路:

  1. 对每个输入的数字,提取其所有数位
  2. 统计:
    • 总数位个数(flag)
    • 可以整除的数位个数(flag1)
  3. 根据统计结果判断类型:
    • 如果 :所有数位都可以整除,输出"G"
    • 如果 :没有数位可以整除,输出"S"
    • 其他情况:部分数位可以整除,输出"H"

代码

#include <iostream>
using namespace std;

void checkNumber(long long num) {
    int totalDigits = 0;    // 总数位数
    int divisibleCount = 0; // 可整除的数位数
    long long temp = num;
    
    while (temp > 0) {
        totalDigits++;
        int digit = temp % 10;
        if (digit == 0 || (digit != 0 && num % digit == 0)) {
            divisibleCount++;
        }
        temp /= 10;
    }
    
    if (totalDigits == divisibleCount) {
        cout << "G" << endl;
    } else if (divisibleCount == 0) {
        cout << "S" << endl;
    } else {
        cout << "H" << endl;
    }
}

int main() {
    int t;
    cin >> t;
    while (t--) {
        long long n;
        cin >> n;
        checkNumber(n);
    }
    return 0;
}
import java.util.Scanner;

public class Main {
    public static void checkNumber(long num) {
        int totalDigits = 0;
        int divisibleCount = 0;
        long temp = num;
        
        while (temp > 0) {
            totalDigits++;
            int digit = (int)(temp % 10);
            if (digit == 0 || (digit != 0 && num % digit == 0)) {
                divisibleCount++;
            }
            temp /= 10;
        }
        
        if (totalDigits == divisibleCount) {
            System.out.println("G");
        } else if (divisibleCount == 0) {
            System.out.println("S");
        } else {
            System.out.println("H");
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while (t-- > 0) {
            long n = sc.nextLong();
            checkNumber(n);
        }
    }
}
def check_number(num):
    total_digits = 0
    divisible_count = 0
    temp = num
    
    while temp > 0:
        total_digits += 1
        digit = temp % 10
        if digit == 0 or (digit != 0 and num % digit == 0):
            divisible_count += 1
        temp //= 10
    
    if total_digits == divisible_count:
        print("G")
    elif divisible_count == 0:
        print("S")
    else:
        print("H")

t = int(input())
for _ in range(t):
    n = int(input())
    check_number(n)

算法及复杂度

  • 算法:数位分解 + 整除判断
  • 时间复杂度: - 为测试用例数,每个数字需要 次操作提取数位
  • 空间复杂度: - 只使用了常数个变量