【leetcode】2269. 找到一个数字的K美丽值

题目描述

leetcode.cn/problems/…/description

思路

水题, 数字类型转为字符切片后再转回数字, 看能否整除.

240转为字符串"240"切片"24"转为数字24240 \xrightarrow{转为字符串} "240" \xrightarrow{切片} "24" \xrightarrow{转为数字} 24

代码

rs:

impl Solution {
    pub fn divisor_substrings(num: i32, k: i32) -> i32 {
        let s: String = num.to_string();
        let mut ans: i32 = 0;

        for i in 0..(s.len() - (k - 1) as usize) {
            let now = s[i..(i + k as usize)].parse::<i32>().unwrap();
            if now == 0 {
                continue;
            }
            if num % now == 0 {
                ans += 1;
            }
        }

        ans
    }
}

py:

class Solution:
    def divisorSubstrings(self, num: int, k: int) -> int:
        s = str(num)
        ans = 0
        n = len(s)

        for i in range(n - k + 1):
            now = int(s[i : i + k])
            if not now == 0 and num % now == 0:
                ans += 1
        return ans