2020.4.8 Huawei Test Two Questions (Java Implementation)

1. The compiler finds the total number of IDs

Xiaohua has designed a compiled language that supports up to N characters with different characters. The length of the ID composed of these characters is "1 <length <L". Find out how many IDs the designed language can make up.

  • Idea: modulus of large number + combination number
import java.util.Scanner;
public class Test1 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Long mod = 1000000007l;
        while (input.hasNext()) {
            Long n = input.nextLong();
            Long l = input.nextLong();
            if (n == 0 && l == 0) {
                break;
            }
            Long sum = 0l;
            Long k = n;
            while(l>0){
                sum+=k;
                sum%=mod;
                k=k*n%mod;
                l--;
            }
            System.out.println(sum);
        }
    }
}

Result ac

2. The largest binary string

It is known that the length of a string composed of 0 and 1 is n, and the following two operations can be performed:
(1) Any random "00" can be changed to "10";
(2) Any random "10" can be changed to " 01 "
What is the maximum value of this binary number through a wave of operations?

  • Idea: The key point is to judge two conditions. The first direct change will always be bigger. The premise of using the second operation is that "10" is in front of "0" to ensure ch [k] and ch [k +1] You can perform the first operation to make the string value larger.
import java.util.Scanner;
public class Test2{
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int t = input.nextInt();
        for(int i=0; i<t; i++) {
            int n = input.nextInt();
            String s = input.next();
            char[] ch = new char[10000];
            for (int j=0; j<n; j++) {
                ch[j] = s.charAt(j);
            }
            for (int k=0; k<n; k++) {
                if (ch[k] == '0' && ch[k + 1] == '0') ch[k] = '1';
                else if(ch[k]=='0' && ch[k+1] == '1' && ch[k+2] == '0'){
                    ch[k] = '1'; ch[k+1] = '0';ch[k+2] = '1';
                }
            }
            for (int k = 0; k < n; k++) {
                System.out.print(ch[k]);
            }
            System.out.println();
        }
    }
}

The result is that the case has passed 70%; after the exam, I continue to think, thinking that the boundary of the "10" to "01" situation is not well considered. Only when k + 2 <n, ch [k + 2] is necessary to exchange

Published 27 original articles · praised 4 · visits 2178

Guess you like

Origin blog.csdn.net/smile001isme/article/details/105400504