Special base conversion

Xiao Ming uses the letter A to correspond to the number 1, B to 2, and so on, with Z to 26. For numbers above 27, Xiao Ming uses a string of two or more digits to correspond. For example, AA corresponds to 27, AB corresponds to 28, AZ corresponds to 52, and LQ corresponds to 329. What is the string corresponding to 2019?

Encountered similar questions many times, let’s summarize

Think about it, how does the decimal number get the number on each digit?

First, take the remainder of n to 10 to get the number on each digit, then divide by 10... until n becomes 0, save it in the array and output in reverse order.

while (n > 0) {
    
    
	s[idx++] = n % 10;
	n /= 10;;
}
for (int i = idx - 1; i >= 0; i--)
	cout << s[i];
cout << endl;

We similarly, take the remainder of n to 26, get the number on each digit, and divide by 26...

But we find that the number on each digit is 1-26, and there is no character representing 0. What should we do?

Operate after subtracting 1 from n

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

char s[105]; 

int main(void)
{
    
    
	int n, idx = 0;
	cin >> n;
	while (n > 0) {
    
    
		s[idx++] = 'a' + (n - 1) % 26;
		n = (n - 1) / 26;
	}
	for (int i = idx - 1; i >= 0; i--) {
    
    
		cout << s[i];
	}
	cout << endl;
	
	return 0;
}

The above code is in reverse order, and it needs to be stored in an array, and then output in reverse order, which is more troublesome.

Use dfs to improve it, use recursive writing, always find the last ones digit, and then output in turn

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

void dfs(int n)
{
    
    
	if (n > 26) dfs((n - 1) / 26);
	putchar('a' + (n - 1) % 26);
}

int main(void)
{
    
    
	int n;
	cin >> n;
	dfs(n);
	cout << endl;
	
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43772166/article/details/109105331