PAT grade B experience (under update)

Posted by neverett on Sat, 05 Mar 2022 06:14:38 +0100

1002 write this number

c + + number and string conversion

Method 1: use stringstream: add header file #include

  1. Number to string

    #include <string>
    #include <sstream>
    
    int main(){
        double a = 123.32;
        string res;
        stringstream ss;          //Define stream ss
        ss << a;                  //Convert number a to stream ss
        ss >> res;                //Convert stream ss to string
        return 0;
    }
    
  2. String to number

    #include <string>
    #include <sstream>
    
    int main(){
        double a ;
        string res= "123.32";
        stringstream ss;  
        ss << res;                  
        ss >> a;
        return 0;
    }
    
    //A method is wrapped here to convert a one digit number into a two digit string
    //0->"00"    1->''01"
    string transform(int num)
    {
         string res;
         stringstream ss;
         ss<<num;
         ss>>res;
         if(num<10){
          res="0"+res;
         }
    	return res;
    }
    

Method 2: using sprintf() function and sscanf() function

  1. sprintf() is used to convert numbers to strings

    \#include <iostream>
    \#include <string>
    using namespace std;
    
    int main()
    {
    	char str[10];
        int a=1234321;
        //Convert integer to string
        sprintf(str,"%d",a);
        int len=strlen(str);
        cout<<"character string"<<str<<endl;
        cout<<"length"<<len<<endl;
        
        char str1[10];
        double b=123.321;
        //Convert floating point numbers to strings
        sprintf(str1,"%.3lf",b);
        int len1=strlen(str1);
        cout<<"character string"<<str1<<endl;
        cout<<"length"<<len1<<endl;
        return 0;
    }
    

  2. sscanf() is used to convert a string to a number

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
    	char str[]="1234321";
    	int a;
    	sscanf(str,"%d",&a);
    	cout<<a<<endl;
    
    	char str1[]="123.321";
    	double b;
        sscanf(str1,"%lf",&b);
        cout<<b<<endl;
        return 0;
    }
    

1003 I want to pass!

Pit: note that the input string is empty or the string length is less than 3!!!

1004 score ranking

If in C + +, use CIN > > str; If this method is used to receive the string, the entered STR cannot contain spaces, otherwise it will cut the whole string into several segments according to the spaces. If you want to enter a string with spaces, you need to use the getline() function.

1007 prime pair conjecture

Prime number is defined as a natural number greater than 1, which has no other factors except 1 and itself. Such a number is called prime number. Prime numbers within 50: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47.

A number, if there is a factor, should be within its square root, otherwise there is no factor. So there must be a factor not greater than the square root of m. Therefore, to judge whether m is a prime number, just try to divide it to the square root of m, not to m-1.

Conclusion: the key is to judge whether the code segment of prime number can be remembered as common sense.

bool isPrime2(int n){
	bool yes=true;
    for(int i=2;i<=sqrt(n);i++){
        if(n%i==0){
            yes=false;
            break;
        }
    }
    return yes;
}

1008 circular right shift of array elements

Pit point: don't take it for granted that n > m, so when m > N, m needs to be treated, that is, the residual calculation M=M%N.

1009 irony

c + + input problem - enter to judge the end of current input:

while (cin >> s) {
    cout << s << endl;
    vec.push_back(s);
    if (cin.get() == '\n') //
        break;
}

1010 derivation of univariate polynomial

  1. Special judgment 0.
  2. No spaces are output at the end.

1011 A+B and C

  1. In C + +, int occupies 4 bytes and 32 bits, and the data range is - 2 147 483 648 ~ 2 147 483 647 [- 231 ~ 231-1]. Int occupies 2 bytes and 16 bits, and the data range is - 3276832767 [- 2 ^ 152 ^ 15-1].
  2. 2 ^ 31 = 2 147 483 648, long integer is required.

1013 prime number

The correct idea should be to find the first 10000 prime and store it in the array, rather than judge whether it is between the m and n in the cycle of determining the prime.

1015 theory of virtue and talent

  1. Define structure array:

    struct info {
    	string num;
    	int de;
    	int cai;
    	int sum;
    	int cla; //category
    }stu[100001];
    
  2. Sort structure array:

    //Custom collation
    bool cmp(info a, info b) {
    	if (a.cla != b.cla) return a.cla < b.cla;
    	else if (a.sum != b.sum) return a.sum > b.sum;
    	else if (a.de != b.de) return a.de > b.de;
    	else return a.num < b.num;
    }
    
    sort(stu, stu + N, cmp);
    

1019 digital black hole

Add 0 before the number:

#include <iostream>
using namespace std;
void main()
{
     int hour=9;
     char acHour[8]={0};
     sprintf(acHour, "%02d", hour);
     cout<<acHour;
}

1019 digital black hole

C + + sort string strings: use sort(s.begin(),s.end());

1020 moon cake

Pit: demand may be greater than inventory.

1022 D-ary A+B

Pit: A+B=0 needs to be considered.

Note: when defining an array, it can be slightly larger, otherwise it is easy to report an error that the array is out of bounds.

1023 minimum decimals

Question: why use INT_MAX will report an error??

1024 scientific counting method

Keep 2 decimal places when outputting C + + key codes:

#include <iomanip>

cout << setiosflags(ios::fixed) << setprecision(2);
cout << 1.23565 << endl;

1026 program running time

Rounding function:

  1. floor -- the largest integer not greater than the argument
  2. ceil -- the largest integer not less than the independent variable
  3. Round -- round to the nearest integer

1028 census

Pit: when the valid value is 0, only 0 is output, and no name is output. It is also not allowed to leave the name blank.

1029 old keyboard

unordered_set printout Code:

#include <unordered_set>
unordered_set<char> wrong;
for (auto iter = wrong.begin(); iter != wrong.end(); iter++)
	cout << *iter;

1033 old keyboard typing

Pit: maybe no key on the old keyboard is bad, so the first line is empty, so you should use getline(cin,s) to enter the string instead of cin.

1034 four operations of rational numbers

Pit: measuring point 2 fails. Because the addition, subtraction, multiplication and division of two ints may exceed the maximum range of ints, all data can be of long long int type (long long).

Note: during division operation, the denominator may be negative, so the code is different from addition, subtraction and multiplication:

simplify(a, b); cout << " / "; simplify(c, d); cout << " = ";
	if (c > 0)
		simplify(a * d, b * c);
	else if (c < 0)
		simplify((-1) * a * d, abs(b * c));
	else
		cout << "Inf";
	cout << endl;

1041 examination seat number

Sort map by value:

//map sort by value
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
 
typedef pair<string, int> PAIR;  
 
int cmp(const PAIR& x, const PAIR& y)//Comparison function for PAIR
{  
    return x.second > y.second;  //From big to small
}  
 
int main() {  
  map<string,int> nmap; 
 
  nmap["LiMin"] = 90;  
  nmap["ZiLinMi"] = 79;  
  nmap["BoB"] = 92;  
  nmap.insert(make_pair("Bing",99));  
  nmap.insert(make_pair("Albert",86));  
  //Transfer the elements in the map to the vector   
  vector<PAIR> vec(nmap.begin(),nmap.end());
  sort(vec.begin(), vec.end(), cmp); //sort
  
  for (size_t i = 0; i != vec.size(); ++i) {  //output
       cout << vec[i].first <<" "<<vec[i].second<<endl;  
  }  
 
  return 0;  
}

1044 Mars digital

Pit:

  1. The number 0 corresponds to the length of Martian, not 3, but 4 ("tret").
  2. Martian carry has no 0. For example, 26 inputs hel instead of hel tret (when an integer multiple of 13, the subsequent output does not have 'tret'.)
  3. In the code, if you enter cin first and then traverse the input getline later, you will read in one less line, because cin will stop when it encounters \ n, resulting in the line feed character in the first line not being read in. Therefore, if cin is used earlier, you need to add a line of getchar(); before using getline;, Or use scanf ('% d \ n', & n);

Topics: C++ Programming Algorithm