top1编程
← 返回题目
题解

【入门】找数

1 条题解

  • 0
    @ 2026-7-28 22:44:53
    #include <bits/stdc++.h>
    using namespace std;
    
    int f(int n) {
    if (n == 0) { // 递归终止条件:当n减至0时结束递归
        return 0;
    }
    
    int q = n / 1000;
    int b = n / 100 % 10;
    int s = n / 10 % 10;
    int g = n % 10;
    int x = q + b + s + g;
    
    if (x % 2 != 0 && x % 5 != 0) {
        return 1 + f(n - 1); 
    // 如果x不能同时被2和5整除,则递归调用f(n-1),并加上当前数的贡献1
    } 
    else {
        return f(n - 1); // 否则只递归调用f(n-1),不加当前数的贡献
    }
    }
    
    int main() {
    int n;
    cin >> n;
    
    int c =f(n);
    cout << c << endl;
    
    return 0;
    }
    
    • 1