Given integer n find the nth string in this sequence A , B , C , . . . , Z , AA , AB , AC , . . . , ZZ , AAA , AAB , . . . AAZ , ABA . . .














































Given integer n find the nth string in this sequence A , B , C , . . . , Z , AA , AB , AC , . . . , ZZ , AAA , AAB , . . . AAZ , ABA . . .



Given integer n find the nth string in this sequence A , B , C , . . . , Z , AA , AB , AC , . . . , ZZ , AAA , AAB , . . . AAZ , ABA . . .

Examples:

Input: N
Output: Nth string

Input: 1
Output: A

Input: 704
Output: AAB





Approach:

  1. We will be constructing nth string from back.
  2. Make a string of 26 alphabets named alpha[]={A , B .. , Z}.
  3. If n<=26 print alpha[n-1].
  4. Else decrease n by 1 and add alpha[n%26] to string and repeat above steps for n/26 till n>0.
  5. Reverse the generated string.

#include <bits/stdc++.h>

using namespace std;

string findString( int n)
{
  string alpha;// string of 26 alphabets from A to Z.
  
  for(char i='A';i<='Z';i++)
    alpha += i;
  
  string ans;
  //If n<=26 we can directly tell the nth string
  if(n <= 26)
  {
    ans += alpha[n-1];
    return ans;
  }
  while( n > 0 )
  {
        ans += alpha[(--n)%26];
        n = n/26;
  }
  reverse ( ans.begin() , ans.end() );
  return ans;
}

int main()
{
  int n=4;
  //cin>>n;
  cout<<findString(n);
  return 0;
}
//Output : D



Comments