[Ybt Advanced 2-1-1] [luogu P1307] Digital inversion

Digital inversion

Topic link: ybt efficient advanced 2-1-1 / luogu P1307

Topic

Given an integer, invert the digits of the number to get a new number.

The new number should also satisfy the common form of integers, that is, unless the original number is given as zero, the highest digit of the new number obtained after the inversion should not be zero.

Idea 1

Think of fast reading, and press fast reading, first deal with the negative sign (if any), and then press fast reading to reverse it.

Fast reading is from left to right (from high to low), then you go from right to left (from low to high).

This is faster, but it won’t work if the number of digits is large.

Code 1

#include<cstdio>

using namespace std;

int n, nn;

int main() {
    
    
	scanf("%d", &n);
	
	if (n < 0) {
    
    
		n = -n;
		printf("-");
	}
	
	while (n) {
    
    
		nn = nn * 10 + (n % 10);
		n /= 10;
	}
	
	printf("%d", nn);
	
	return 0;
} 

Idea 2

If the number of digits is large, we consider using a string to do it.

In a similar way, first judge the negative sign and deal with it.

Then flip it and output from right to left.

But to deal with the highest bit 0 00 , then if there is a segment of0 0 atthe beginning0 string, do not output it.
(But if the whole is0 0If 0 , you still have to leave a0 00 )

Code 2

#include<cstdio>
#include<cstring>

using namespace std;

int last = 0, size;
char c[11];

int main() {
    
    
	scanf("%s", c);
	
	if (c[0] == '-') {
    
    
		printf("-");
		last = 1;
	}
	
	size = strlen(c);
	while (c[size - 1] == '0' && size - 1 > last) size--;
	
	for (int j = size - 1; j >= last; j--)
		putchar(c[j]);
	
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43346722/article/details/112724345