跳转至

2520. 统计能整除数字的位数

题目描述

给你一个整数 num ,返回 num 中能整除 num 的数位的数目。

如果满足 nums % val == 0 ,则认为整数 val 可以整除 nums

 

示例 1:

输入:num = 7
输出:1
解释:7 被自己整除,因此答案是 1 。

示例 2:

输入:num = 121
输出:2
解释:121 可以被 1 整除,但无法被 2 整除。由于 1 出现两次,所以返回 2 。

示例 3:

输入:num = 1248
输出:4
解释:1248 可以被它每一位上的数字整除,因此答案是 4 。

 

提示:

  • 1 <= num <= 109
  • num 的数位中不含 0

解法

方法一:枚举

我们直接枚举整数 $num$ 的每一位上的数 $val$,若 $val$ 能够整除 $num$,那么答案加一。

枚举结束后,返回答案即可。

时间复杂度 $O(\log num)$,空间复杂度 $O(1)$。

1
2
3
4
5
6
7
class Solution:
    def countDigits(self, num: int) -> int:
        ans, x = 0, num
        while x:
            x, val = divmod(x, 10)
            ans += num % val == 0
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public int countDigits(int num) {
        int ans = 0;
        for (int x = num; x > 0; x /= 10) {
            if (num % (x % 10) == 0) {
                ++ans;
            }
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
public:
    int countDigits(int num) {
        int ans = 0;
        for (int x = num; x > 0; x /= 10) {
            if (num % (x % 10) == 0) {
                ++ans;
            }
        }
        return ans;
    }
};
1
2
3
4
5
6
7
8
func countDigits(num int) (ans int) {
    for x := num; x > 0; x /= 10 {
        if num%(x%10) == 0 {
            ans++
        }
    }
    return
}
1
2
3
4
5
6
7
8
9
function countDigits(num: number): number {
    let ans = 0;
    for (let x = num; x; x = (x / 10) | 0) {
        if (num % (x % 10) === 0) {
            ++ans;
        }
    }
    return ans;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
impl Solution {
    pub fn count_digits(num: i32) -> i32 {
        let mut ans = 0;
        let mut cur = num;
        while cur != 0 {
            if num % (cur % 10) == 0 {
                ans += 1;
            }
            cur /= 10;
        }
        ans
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
int countDigits(int num) {
    int ans = 0;
    int cur = num;
    while (cur) {
        if (num % (cur % 10) == 0) {
            ans++;
        }
        cur /= 10;
    }
    return ans;
}

方法二

1
2
3
4
5
6
7
8
9
function countDigits(num: number): number {
    let ans = 0;
    for (const s of num.toString()) {
        if (num % Number(s) === 0) {
            ans++;
        }
    }
    return ans;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
impl Solution {
    pub fn count_digits(num: i32) -> i32 {
        num
            .to_string()
            .chars()
            .filter(|&c| c != '0')
            .filter(|&c| num % (c.to_digit(10).unwrap() as i32) == 0)
            .count() as i32
    }
}

评论