Huawei machine test online training | problem solving record | HJ01-103

Keywords: C++ leetcode

0. Basic knowledge

0.1. Input and output

0.1.1 basic input and output

  1. Input normal
int n;
cin>>n;
cout<<n;
  1. Enter with spaces
string str;
cin(cin,str);

0.1.2 header file

  1. Common header file
#include<bits/stdc++.h>
using namespace std;

0.2. Common operations on strings

substr

string str='123';
string temp=str.substr(0,1);
//Substr (start position, length) substr(begin_index,length)

substr reference

atoi

string temp='123';
int temp_int=atoi(temp.c_str());
//Pay attention to use c_str()

to_string

int num = 123;
string num_str = to_string(num);

uppercase

transform(str.begin(),str.end(),str.begin(),toupper);

String and number conversion references

0.3. Common operations on vector

0.4. About

1. Introductory questions

HJ7 take approximate value

HJ7 take approximate value
Write a program that accepts a positive floating-point value and outputs the approximate integer value of the value. If the value after the decimal point is greater than or equal to 5, round up; Less than 5, rounded down.
Enter a positive floating point number
Output the approximate integer value of this value 5.5-6

#include<bits/stdc++.h>
using namespace std;
int main()
{
    float n;
    cin>>n;
    cout<<(int(n+0.5))<<endl;
    return 0;
}

HJ15 find the number of 1 when int positive integers are stored in memory

HJ15 find the number of 1 when int positive integers are stored in memory
Enter a positive integer of type int and calculate the number of 1 when the int data is stored in memory.
Enter an integer (type int)
After this number is converted to binary, the number of 1 is output
------------------------------—
Solution:

  1. Convert the decimal number into binary number, take the module first, then divide by 2 to get the number of 1, and finally divide by 2 will become 0, which is the final judgment condition
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    int count=0;
    while(n)
    {
        if(n%2)count++;
        n=n/2;                 
    }
    cout<<count<<endl;
    return 0;
}

------------------------------—

HJ101 enter an integer array and sort ID to sort its elements in ascending or descending order

HJ101 enter an integer array and sort ID to sort its elements in ascending or descending order

Problem solving:

  1. Process input and output
  2. Find out the position of the space, extract the string and convert it into numbers; The first number needs special treatment, and the last one also needs special treatment (you can cut it by pushing the string length into the position assumed to be a space).
  3. Finish sorting
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
        string str1;
        getline(cin,str1);
        string str;
        getline(cin,str);
        int index;
        cin>>index;
        vector<int> blank;
        //Find the position of all spaces
        for(int i=0;i<str.length();i++)
            if(str[i]==' ') blank.push_back(i);
        blank.push_back(str.length());
        
        //Extract the place where each number is located. The first number is specially processed, and the last number is also. Actively input the length of the last position to be processed
        vector<int> answer;
        string temp =str.substr(0,blank[0]);
        int temp_int=atoi(temp.c_str());
        answer.push_back(temp_int);
        for(int i=1;i<blank.size();i++)
        {
           string temp=str.substr(blank[i-1]+1,blank[i]-blank[i-1]-1);
           answer.push_back(atoi(temp.c_str()));//Note that C is added here_ STR can be converted normally
        }
        //sort
        sort(answer.begin(),answer.end());
        if(index) reverse(answer.begin(),answer.end());
        //Processing output
        for(int i=0;i<answer.size();i++) cout<<answer[i]<<' ';
        cout<<endl;
        
        
    }
     return 0;
}

Simple questions

HJ11 digit inverted string simple 55.18%

HJ11 number reversal Add link description

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    string str=to_string(n);
    reverse(str.begin(),str.end());
    cout<<str<<endl;
    return 0;
}

HJ12 string inversion 55.29%

HJ12 string inversion

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string str;
    getline(cin,str);
    reverse(str.begin(),str.end());
    cout<<str<<endl;
    return 0;
}

HJ22 water bottle simulation is 26.35% simple

HJ22 water bottle
As long as there are two bottles of water, you can drink an extra bottle of beverage

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    while(cin>>n&&n!=0)
    {
        int count=0;
        while(n>=2)
        {
            count++;
            n-=2;            
        }
        cout<<count<<endl;
    }
    return 0;
}

⭐ HJ37 statistics the total number of rabbits in each month, and the ranking is simple by 39.23%

I didn't think about it

#include<bits/stdc++.h>
using namespace std;
//Fibonacci sequence function
int getTotalCount(int monthCount)
{
    int F[monthCount + 1];
    F[0] = 1; //The number of rabbits in the first month, the little rabbit was born, and then began to grow up.
    F[1] = 1; //The number of rabbits in the second month, the little rabbit continued to grow up and slowly became an old rabbit.
    F[2] = 2; //The number of rabbits in the third month, the old rabbit began to give birth to little rabbits. The little rabbit born later is similar to the old rabbit.
    for(int i = 3; i < monthCount; i++)
    {
        F[i] = F[i-1] + F[i-2];
    }
    //Returns the total number of rabbits in the monthCount month
    return F[monthCount - 1];
}
//The main function calls the interface of Fibonacci sequence function to get the total number of rabbits per month
int main()
{
    int monthCount;
    while(cin >> monthCount)
    {
        cout << getTotalCount(monthCount) << endl;
    }
    return 0;
}

HJ50 four operation string stack is mathematically simple by 53.71%

⭐ The deformation string of HJ53 Yanghui triangle is 48.69%

This question is to find the law. As long as you write down a few lines, you can see the law of parity, and you only need to write the first few lines in each line, because the question asks the first even index.
So we will find that only when n is 1 and 2, there is no even number, and the rest circulates every four lines according to the law of 2, 3, 2 and 4.
I didn't see it.

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int input;
    int result;
    int tmp[4] = {2,3,2,4};
    while(cin>>input)
    {
        if(input == 1||input == 2)
            result = -1;
        else
            result = tmp[(input -3)%4];
        cout << result <<endl;
    }
    return 0;
}

Reference problem solution

HJ54 expression evaluation string math stack simple 52.83%

HJ56 iNOC product department – complete number calculation is mathematically simple by 45.75%

⭐ HJ61 recursive dynamic programming is 44.67% simple

/*
There are two situations for putting apples. One is that there are empty plates, and the other is that there are apples on each plate.
Let (m,n) represent the total number of placement methods for placing m apples on N plates.
1.Assuming that one plate is empty, the (m,n) problem is transformed into placing m apples on n-1 plates, that is, finding (m,n-1)
2.Assuming that all plates contain apples, there is at least one apple on each plate, that is, there are at most m-n apples left. The problem is to put m-n apples on n plates
 Namely (m-n, n)
*/
#include<bits/stdc++.h>
using namespace std;
int f(int m,int n){
    if(m<0||n<0) return 0;
    else if(m==1||n==1) return 1;
    else if(n<m) return f(m,n-1)+f(m-n,n);
       
}
int main(){
    int m,n;
    while(cin >> m >> n){
        cout << f(m,n) << endl;
    }
    return 0;
}

HJ62 finds one digit in the binary of the input integer, and the operation is 47.32% simple

HJ66 profile recovery string simple 42.32%

HJ72 the problem of buying 100 chickens for 100 yuan is simple 45.02%

#include<bits/stdc++.h>
using namespace std;
//x+y+z==100
//5*x+3*y+z/3==100
//After simplification, X is less than or equal to 14, y is less than or equal to 25, and 7*x+4*y==100 can be satisfied
int main()
{
    int n;
    if(cin>>n)
    {
        for(int x=0;x<=14;x++)
            for(int y=0;y<=25;y++)
                if(7*x+4*y==100) 
                {
                    int z=100-x-y;
                    cout<<x<<' '<<y<<' '<<z<<endl;
                }         
    }
    return 0;
}

HJ73 calculation of date to day conversion string is simple by 40.22%

⭐ HJ74 parameter parsing string is 35.64% simple

Solution:

  1. I didn't expect to calculate the count and output separately
  2. I didn't expect to use the two symbols "" to clamp the output. I just wanted to consider spaces
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string input;
    while(getline(cin,input))
    {
        //Number of Statistics
        int length = input.length();
        int num = 0;
        for(int i=0; i<length; i++)
        {
            if(input[i] == '"')
            {
                i++;
                while(input[i]!='"') i++;
            }
            else if(input[i] == ' ')
                num++;
        }
        cout<<num+1<<endl;
        //output
         for(int i=0; i<length; i++)
        {
            if(input[i] == '"')
            {
                i++;
                while(input[i]!='"')
                {
                    cout<<input[i];
                    i++;
                }
            }
            else if(input[i] ==' ')
                cout<<endl;
            else
                cout<<input[i];
        }
        cout<<endl;
    }
    return 0;
}

HJ75 ⭐ Common string calculation is 39.13% simpler

#include <bits/stdc++.h>
using namespace std;

int main()
{
    std::string a;
    std::string b;
    getline(std::cin, a);
    getline(std::cin, b);
    int max_len = 0;
    std::string sub_str = "";

    for(int i=0; i<a.length(); i++)
    {
        for(int j=0; j<b.length(); j++)
        {
            if(a[i] == b[j])
            {
                for(int m=i, n=j; m<a.length(), n<b.length(); m++, n++)
                {
                    if(a[m] != b[n])
                    {
                        break;
                    }
                    if((m - i + 1) > max_len)
                    {
                        max_len = m - i + 1;
                        sub_str = a.substr(i, m+1);
                    }
                }
            }
        }
    }
    std::cout << max_len << std::endl;
    //std::cout << sub_str << std::endl;
}

HJ76 nicoches theorem is mathematically simple 42.94%

HJ83 2D array operation is 27.33% simple

HJ84 counts the number of uppercase letters, and the string is simple by 39.97%

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string str;
    while(getline(cin,str))
    {
        int count=0;
        for(int i=0;i<str.length();i++)
            if(str[i]>='A'&&str[i]<='Z')
                count++;
        cout<<count<<endl;
    }
     return 0;
}

HJ85 longest palindrome substring string exhaustive simple 37.98%

HJ86 is 40.91% simpler to calculate the maximum continuous bit number

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int n;
    while(cin>>n)
    {
        vector<int>record;
        while(n)
        {            
            record.push_back(n%2);
            n=n/2;
        }
        reverse(record.begin(),record.end());
        vector<int>index;
        for(int i=0;i<record.size();i++)
            if(record[i]==0) index.push_back(i);
        index.push_back(record.size());
        int max=index[0];
        for(int i=1;i<index.size();i++)
            if(index[i]-index[i-1]>max) max=index[i]-index[i-1]-1;
        cout<<max<<endl;
        //cout<<max<<endl;
    }
    return 0;
}

HJ87 password strength level string simple 30.95%

#include<bits/stdc++.h>
using namespace std;
int main(){
     string s;
    while(getline(cin,s))
    {
        int score=0;
        int num=0;
        int schar=0;
        int bchar=0;
        int flag=0;
        //1. Length
        if(s.size()<=4)score+=5;
        else if(s.size()>=5&&s.size()<=7)score+=10;
        else score+=25;
        //Letter, symbol, number traversal
        for(int i=0;i<s.size();i++)
        {
            if(s[i]>='0'&&s[i]<='9'){
                num+=1;
            }else if(s[i]>='a'&&s[i]<='z')
            {
                schar++;
            }else if(s[i]>='A'&&s[i]<='Z')
            {
                bchar++;
            }else flag++;
        }
        //Letter score
        if(schar==0&&bchar==0){}
        else if((schar!=0&&bchar==0)||(schar==0&&bchar!=0))
        {
            //Single letter
            score+=10;
        }else score+=20;
        
        //Numerical score
        if(num>1)score+=20;
        else if(num==1)score+=10;
        
        //Symbolic score
        if(flag>1)score+=25;
        else if(flag==1)score+=10;
        
        //reward
        if(schar&&bchar&&flag&&num)score+=5;
        else if((schar||bchar)&&flag&&num)score+=3;
        else if((schar||bchar)&&num)score+=2;
        
        //score
        if(score>=90)cout<<"VERY_SECURE"<<endl;
        else if(score>=80)cout<<"SECURE"<<endl;
        else if(score>=70)cout<<"VERY_STRONG"<<endl;
        else if(score>=60)cout<<"STRONG"<<endl;
        else if(score>=50)cout<<"AVERAGE"<<endl;
        else if(score>=25)cout<<"WEAK"<<endl;
        else cout<<"VERY_WEAK"<<endl;
    }
}

The scheme of HJ91 taking the grid is 43.14% simpler than the digital character string

HJ97 recording negative average positive array is simple by 19.34%

HJ100 equal difference sequence is mathematically simple by 38.17%

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
        int sum=n*(n-1)*3/2+2*n;
        cout<<sum<<endl;
    }
    return 0;
}

HJ106 character reverse order string simple 42.93%

HJ106 character reverse order

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string str;
    getline(cin,str);
    reverse(str.begin(),str.end());
    cout<<str<<endl;
    return 0;
}

HJ108 recursive mathematics for finding the least common multiple

Solution:

  1. There are two cases:
  • ab can be divisible, and the maximum number is the minimum common divisor
  • ab is not divisible. The least common multiple is an integer multiple of a larger number. a*b is the common multiple of a and b, but it is not necessarily the smallest.
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int a,b;cin>>a>>b;
    
    if(max(a,b)%min(a,b)==0) //Two numbers can be divided, and the larger number is the least common multiple
    {
        cout<<max(a,b);
    }    
    else
    {   
        for(int i=1; i<= min(a,b);i++)
        {
            //The least common multiple is an integer multiple of a larger number. a*b is the common multiple of a and b, but it is not necessarily the smallest.
            int num = i*max(a,b);
            if(num%a==0 && num%b==0)
            {
                cout<<num;
                break; //The first time you find a common multiple, you jump out of the loop
            } 
        }
    }
    return 0;
}

------------------------------—
------------------------------—
------------------------------—
------------------------------—
------------------------------—
------------------------------—
------------------------------—
------------------------------—
------------------------------—
------------------------------—

Medium question

HJ5 hex conversion string medium 30.33%

#include<bits/stdc++.h>
#include<string>
using namespace std;
int count(string str)
{
    int sum=0;
    for(int i=0;i<str.length();i++)
    {
        if(str[i]=='A') sum+=10*pow(16,i);
        else if(str[i]=='B') sum+=11*pow(16,i);
        else if(str[i]=='C') sum+=12*pow(16,i);
        else if(str[i]=='D') sum+=13*pow(16,i);
        else if(str[i]=='E') sum+=14*pow(16,i);
        else if(str[i]=='F') sum+=15*pow(16,i);
        else sum+=(str[i]-'0')*pow(16,i);                
    }
    return sum;
}
int main()
{
    string str;
    while(getline(cin,str))
    {
        str=str.substr(2,str.length());
        reverse(str.begin(),str.end());
        int sum=count(str);
        cout<<sum<<endl;       
    }
    
    
}

⭐ HJ6 prime factor ranking medium 25.93%

#include<bits/stdc++.h>
using namespace std;
int main()
{
    long num;
    while (cin>>num) 
    {
        int maxi = sqrt(num);
        for (int i = 2; i <= maxi; i++) {
            while (!(num % i)) { //Prime numbers are composed of prime numbers. If you continue to divide smaller prime numbers, large prime numbers will not appear
                num /= i;
                cout<<i<<' ';//Find the prime number and divide it until there is no prime factor
            }
        }
        if (num != 1) 
            cout<<num<<' '<<endl;//num itself is a prime number

        cout<<endl;
    }
    return 0;
}

HJ8 consolidated table record medium 32.99%

HJ9 extracts non repetitive integer array hash bit operation, medium 40.27%

HJ10 character count string hash medium 43.31%

HJ14 string sorting medium 38.08%

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
        vector<string> record;
        string str;
        for(int i=0;i<n;i++)
        {
            cin>>str;
            record.push_back(str);
        }
        sort(record.begin(),record.end());
        for(int i=0;i<record.size();i++)
            cout<<record[i]<<endl;
    }
    return 0;
}

HJ16 shopping list dynamic planning medium 19.61%

HJ21 simple password cracking string medium 38.27%

HJ26 string sorting medium 33.56%

HJ34 picture sorting string medium 42.77%

HJ35 serpentine matrix array medium 39.60%

HJ36 string encryption string medium 37.67%

HJ38 calculates that the distance experienced by the small ball after landing for 5 times and the height of the fifth rebound are medium by 35.11%

HJ40 input a line of characters and count the number of strings containing English letters, spaces, numbers and other characters respectively. The average is 40.13%

HJ43 maze problem ranking medium 33.63%

HJ45 name beauty string medium 34.29%

HJ46 intercepting string by byte 41.95%

HJ48 deletes 34.81% of the nodes with the specified value from the one-way linked list

HJ52 calculate the distance between strings 37.26%

HJ55 pick 7 exhaustive mathematics medium 40.47%

HJ57 high precision integer addition string medium 35.87%

HJ59 find the first character in the string that appears only once. The string is medium 30.02%

HJ60 searches for the two prime numbers that make up an even number, and the exhaustive mathematics is medium 41.17%

HJ63 DNA sequence string medium 39.37%

HJ64 MP3 cursor position array medium 29.67%

HJ65 finds the longest common substring in two strings a and B, 33.79%

HJ67 24 point game algorithm search dfs medium 34.66%

HJ69 matrix multiplication array medium 40.92%

HJ70 matrix multiplication calculation amount estimation string medium 38.65%

HJ71 string wildcard string medium 30.60%

HJ88 POKER SIZE string queue linked list stack medium 32.57%

HJ90 legal IP string linked list stack queue medium 35.19%

HJ96 indicates that the numeric string is medium 30.72%

HJ98 vending system string medium 25.15%

HJ99 moderate self-reliance 35.34%

HJ102 character statistics string sorting medium 28.64%

HJ103 Redraiment has a medium ranking of 26.53%

HJ107 solving cube root mathematics dichotomy medium 27.30%

------------------------------—

More difficult

The length of the last word of HJ1 string is 29.61%

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string str;
    while(getline(cin,str))
    {
        int flag=0;
        for(int i=str.length()-1;i>0;i--)
        {
            if(str[i]==' ')
            {
                int num=str.length()-i-1;
                cout<<num<<endl;
                flag=1;
                break;
            }
        }
        if(!flag) cout<<str.length()<<endl;
    }
    return 0;
}

HJ2 it is difficult to calculate the number of characters string hash 28.00%

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string str;
    char compare;
    while(getline(cin,str)&&cin>>compare)
    {
        int count=0;
        for(int i=0;i<str.length();i++)
            if(str[i]==compare||str[i]-'a'+'A'==compare||str[i]-'A'+'a'==compare)
               count++;
        cout<<count<<endl;
    }
}

⭐ The random number group of HJ3 is 19.88% more difficult

Solution:

  1. Auto sort using set
  2. insert iterator
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
        set<int> record;
        while(n--)
        {
            int num;
            cin>>num;
            record.insert(num);//--------------------------------------------
            //if(find(record.begin(),record.end())==record.end())record.push_back(num);
        }
        set<int>::iterator it;
        for(it=record.begin();it!=record.end();it++)//--------------------------------------------
            cout<<*it<<endl;
    }
    return 0;
}

HJ4 string is difficult to separate strings 26.23%
HJ13 sentence reverse order array is difficult 36.49%
HJ17 coordinate moving string is difficult 21.65%
HJ20 password verification qualified program array string is difficult 26.20%
HJ23 it is difficult to delete the character string with the least number of occurrences in the string by 29.92%
HJ24 chorus queue dynamic planning is difficult 24.42%
HJ25 data sorting is difficult 20.73%
HJ29 string encryption and decryption is difficult 25.10%
HJ30 string merging is difficult to sort strings 25.02%
HJ32 password is difficult to intercept strings 26.13%
HJ33 conversion string between integer and IP address is difficult 28.65%
HJ39 determines whether two IP S belong to the same subnet. String simulation is difficult 16.43%
HJ41 weighs that the weight string is difficult 37.03%
HJ42 learning English strings is difficult 28.37%
HJ51 outputs the chain list of the penultimate node in the one-way lin k ed list, which is 24.28% difficult
HJ58 inputs n integers and outputs the smallest k arrays, which is 30.11%
HJ68 score ranking is difficult 23.51%
It is difficult for HJ77 train to enter the station stack 42.27%
HJ80 integer array consolidation array sorting is difficult 30.46%
HJ81 string is difficult to match 28.11%
HJ92 it is difficult to find the longest consecutive number string in the string, 27.75%
HJ93 array grouping string recursion is difficult 30.23%
HJ94 ticket counting is difficult 26.11%
HJ95 RMB string conversion is difficult 26.66%
HJ105 is difficult to record negative average positive II array 25.23%

HJ23 deletes the character string with the least number of occurrences in the string

HJ23 deletes the character with the least number of occurrences in the string

#include<bits/stdc++.h>
using namespace std;
int main()
{
   string str;
    while(cin>>str)
    {
        //Stores the degree of each character
        map<char,int> map;        
        for(int i=0;i<str.length();i++)
            map[str[i]]++;
        
        //Find the smallest degree
        int min=str.length();
        for(int i=0;i<str.length();i++)
            if(map[str[i]]<min) min=map[str[i]];
        
        //Store characters whose degree is not the smallest
        vector<char> record;
        for(int i=0;i<str.length();i++)
            if(map[str[i]]!=min) record.push_back(str[i]);
        
        //Output results
        for(int i=0;i<record.size();i++)
            cout<<record[i];
        cout<<endl;
    }
    return 0;
}

Posted by Greg_BigPhpAmat on Wed, 29 Sep 2021 21:17:20 -0700