[LeetCode] 1399. Count the number of the largest group (C++)

1 topic description

Give you an integer n. Please find the sum of the digits under the decimal representation of each integer from 1 to n (add the digits on each digit), and then put the digits and equal numbers in the same group.
Please count the number of digits in each group, and return how many groups have the largest number of digits in parallel.

2 Example description

2.1 Example 1

Input: n = 13
Output: 4
Explanation: There are a total of 9 groups. After the digits from 1 to 13 are added, these groups are:
[1,10], [2,11], [3,12], [4 ,13], [5], [6], [7], [8], [9]. In total, 4 groups have the most numbers tied together.

2.2 Example 2

Input: n = 2
Output: 2
Explanation: There are 2 groups [1], [2] of size 1 in total.

2.3 Example 3

Input: n = 15
Output: 6

2.4 Example 4

Input: n = 24
Output: 5

3 Problem solving tips

1 <= n <= 10^4

4 Problem-solving ideas

Create a list to store the number, compare it with the largest item after sorting, and output the number after comparison.

5 Detailed source code (C++)

class Solution {
    
    
public:
    int countLargestGroup(int n) {
    
    
        int count = 1 ; //计数数字数目并列最多的组
        int digital_sum[36] = {
    
     0 } ; //存放数位和,digital_sum[0]存放数位和为1的数,以此类推,最大数位和的数为9999,和为36
        for ( int i = 1 ; i <= n ; i ++ )
        {
    
    
            int temp = i , index = 0 ;
            while( temp )
            {
    
    
                index = index + temp % 10 ;
                temp = temp / 10 ;
            }
            digital_sum[index - 1] ++ ;
        }
        sort( digital_sum , digital_sum + 36 ) ;
        for ( int i = 34 ; i > 0 ; i-- )
        {
    
    
            if ( digital_sum[i] == digital_sum[35] )
            {
    
    
                count ++ ;
            }
        }
        return count ;
    }
};

Guess you like

Origin blog.csdn.net/Gyangxixi/article/details/114314935