Welcome to Subscribe On Youtube

3945. Digit Frequency Score

Description

You are given an integer n.

The score of n is defined as the sum of d * freq(d) over all distinct digits d, where freq(d) denotes the number of times the digit d appears in n.

Return an integer denoting the score of n.

 

Example 1:

Input: n = 122

Output: 5

Explanation:

  • The digit 1 appears 1 time, contributing 1 * 1 = 1.
  • The digit 2 appears 2 times, contributing 2 * 2 = 4.
  • Thus, the score of n is 1 + 4 = 5.

Example 2:

Input: n = 101

Output: 2

Explanation:

  • The digit 0 appears 1 time, contributing 0 * 1 = 0.
  • The digit 1 appears 2 times, contributing 1 * 2 = 2.
  • Thus, the score of n is 2.

 

Constraints:

  • 1 <= n <= 109

Solutions

Solution 1: Simulation

The problem is equivalent to finding the sum of each digit of a number. We can obtain each digit by repeatedly taking the modulus and dividing by 10, and accumulate the result.

The time complexity is $O(\log n)$, where $\log n$ is the number of digits in $n$. The space complexity is $O(1)$.

  • class Solution {
        public int digitFrequencyScore(int n) {
            int ans = 0;
            for (; n > 0; n /= 10) {
                ans += n % 10;
            }
            return ans;
        }
    }
    
  • class Solution {
    public:
        int digitFrequencyScore(int n) {
            int ans = 0;
            for (; n > 0; n /= 10) {
                ans += n % 10;
            }
            return ans;
        }
    };
    
  • class Solution:
        def digitFrequencyScore(self, n: int) -> int:
            ans = 0
            while n:
                n, x = divmod(n, 10)
                ans += x
            return ans
    
    
  • func digitFrequencyScore(n int) (ans int) {
    	for ; n > 0; n /= 10 {
    		ans += n % 10
    	}
    	return
    }
    
  • function digitFrequencyScore(n: number): number {
        let ans = 0;
        for (; n; n = Math.floor(n / 10)) {
            ans += n % 10;
        }
        return ans;
    }
    
    

All Problems

All Solutions