Skip to content

Problem 3: Number of k (100pts)

Problem

Write a function that takes two non-negative integers, n and k, and returns the number of occurrences of k in n.

For example, number_of_k(1234321, 2) returns 2, since 1234321 consists of 1, 2, 3, 4, 3, 2, 1, and there are two 2's in it.

编写一个函数,接受两个非负整数 nk,并返回 kn 中出现的次数。

例如,number_of_k(1234321, 2) 返回 2,因为 12343211, 2, 3, 4, 3, 2, 1 组成,其中有两个 2

def number_of_k(n, k):
    """Return the number of occurrences of k in each digit of a non-negative
    integer n.

    >>> number_of_k(999, 9)
    3
    >>> number_of_k(1234321, 2)
    2
    """
    "*** YOUR CODE HERE ***"

Hints

Hint1: You may want to use a while loop to solve this problem. Be careful when to stop!

Hint2: For a positive integer n (e.g., 123), n % 10 gives you the last digit of n (123 % 10 gets 3), whereas n // 10 gives you all except the last digits of n (123 // 10 gets 12).

Hint3: It is guaranteed that 0 <= k <= 9.

  • 您可能需要使用一个 while 循环来解决此问题。请注意何时停止!

  • 对于一个非负整数 n(例如 123),n % 10 得到 n 的个位数字(123 % 10 得到 3),而 n // 10 得到 n 除个位数字以外的所有数字(123 // 10 得到 12)。

  • k 的输入总满足 0 <= k <= 9

  • 此题可用 str 偷鸡 (但好像被制裁了)

  • 注意 nk 均为 0 时输出为 1

Solutions

使用 while 循环。每次只判断个位数是否与 k 相同,当判断后 n 只剩一位时,所有数位都已经计数,退出循环。

def number_of_k(n, k):
    count = 0
    # Infinite loop until break
    while(True):
        # Get the last digit of n using %
        last_digit = n % 10

        # Check if the last digit is equal to k
        if last_digit == k:
            count += 1

        # Exit the loop when only one digit remains
        if(n < 10): 
            break

        # Remove the last digit from n using //
        n = n // 10

    return count

使用 while 循环,但不使用 break 。需要单独判断最后一位。

def number_of_k(n, k):
    count = 0

    # When n has more than one digits
    while n >= 10:

        last_digit = n % 10
        # We first check the last digit of n
        if last_digit == k:
            count += 1

        # And then drop the last digit of n
        n = n // 10

    # When n has only one digit left
    if n == k:
        count += 1

    return count

直接特判 n == 0 and k == 0 时的情况

def number_of_k(n, k):

    if (n == 0 and k == 0):
        return 1

    count = 0
    # The loop continues as long as there are digits left in n
    while n > 0:
        # Get the last digit of n using %
        last_digit = n % 10

        # Check if the last digit is equal to k
        if last_digit == k:
            count += 1

        # Remove the last digit from n using //
        n = n // 10

    return count

str 偷鸡(使用 count 函数)

def number_of_k(n, k):
    return str(n).count(str(k))