Likou 1689. Ten-the minimum number of binary numbers-C language implementation-medium difficulty questions

topic

Portal

If a decimal number does not contain any leading zeros, and the number on each digit is either 0 or 1, then the number is a decimal-binary number. For example, 101 and 1100 are both ten-binary numbers, but 112 and 3001 are not.
Give you a string n representing a decimal integer, and return the minimum number of decimal-binary numbers whose sum is n.

Example 1:

Input: n = "32"
Output: 3
Explanation: 10 + 11 + 11 = 32

Example 2:

Input: n = "82734"
Output: 8

Example 3:

Input: n = "27346209830709182346"
Output: 9

prompt:

1 <= n.length <= 105
n 仅由数字组成
n 不含任何前导零并总是表示正整数

Source: LeetCode

Problem solving

template

int minPartitions(char * n){
    
    
}

Problem solving ideas

In fact, this question can be understood as asking what is the largest number in the input string, the largest is only 9, so you can establish a loop to traverse backwards

We can decide whether to terminate the loop traversal by judging whether there are any elements in the loop. Every time we traverse, we need to convert the characters into numbers, which is n[i]-'0';

If the 9 is detected in advance, you can jump out directly, thinking that there will be no bigger than 9, saving useless work.

Code

int minPartitions(char * n){
    
    
    int times=0;
    for(int i=0;n[i]!='\0';i++)
    {
    
    
        times=fmax(times,n[i]-'0');
        if(times==9)return times;
    }
    return times;
}

Of course, the for loop can also be implemented as a while.

Guess you like

Origin blog.csdn.net/qq_44922487/article/details/113828404