Minus one operation B~2021.1.6

Title description

Given a non-empty array composed of positive integers, that is, the digits of a positive integer N (1≤N<10​1000​​), the highest digit is stored in the first position of the array, and each array element is only stored One digit.
Request a new array corresponding to N-1 and output it.
Assume that in addition to the integer 0, the first element of the array will not be zero.

Input format

Enter the digits that give a positive integer N in one line, separated by spaces

Output format

Output the digits of N-1, separated by spaces

Input sample

2 8 6 6

Sample output

2 8 6 5

AC code

#include <iostream>
using namespace std;
const int maxn = 1005;
int n[maxn] = {
    
    0};
int main()
{
    
    
	int cnt = 0,num;
	while(cin>>num){
    
    
		n[++cnt] = num;
		if(cin.get() == '\n')	break;
	}
	if(cnt == 1){
    
    
		cout<<n[1] - 1<<' ';
	}
	else{
    
    
		for(int i=cnt;i>=1;i--){
    
    
			if(n[i] != 0){
    
    
				n[i] = n[i] - 1;
				break;
			}
			else{
    
    
				n[i] = 9;
			}
		}
		if(n[1] != 0){
    
    
			for(int i=1;i<=cnt;i++){
    
    
				cout<<n[i]<<' ';
			}
		}
		else{
    
    
			for(int i=2;i<=cnt;i++){
    
    
				cout<<n[i]<<' ';
			}
		}
	}
	return 0;
}

Ideas and explanations

① Thinking: The question itself does not have any difficulty, and the difficulty lies in various points that will block you.
②Explanation:
1) Input:

while(cin>>num){
    
    
	n[++cnt] = num;
	if(cin.get() == '\n')	break;
}

My original input is 1 in the condition of the while loop, even if it forms an infinite loop, the carriage return is captured by cin.get(), so that the break completes the input. However, if the condition is not cin>>num, that is, if it is read to the end of the file, it will run timeout on OJ.
2) Solving: There is no difficulty, it can be solved by any method, it can be regarded as a simplified large integer subtraction, don't forget the special judgment.
3) Perfect AC.

Guess you like

Origin blog.csdn.net/fatfairyyy/article/details/112290921