Skip to main content

Total Decoding Messages

Task: Number of decoding messages from given number(in the form of string), The decoding way is 1 with A, 2 with B ... 26 with Z.

Example:
Input:
1
123
Output:
3 // ABC,LC and AW.

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. using namespace std;
  3. int totalNumberOfWays(char *a,int n)
  4. {
  5.     if(isalpha(n)) return 1;
  6.     if(a[0]=='0') return 0;
  7.     int p=1,q=1,res=1;
  8.     for(int i=1;i<n;i++)
  9.     {
  10.         int t = (a[i-1]-'0')*10+a[i]-'0';
  11.         if(t>=10&&t<=26)
  12.         {
  13.             if(t==10||t==20) res=p;
  14.             else res=p+q;
  15.         }
  16.         else
  17.         {
  18.             if(t%10==0) return 0;
  19.             else res=q;
  20.         }
  21.         p=q;
  22.         q=res;
  23.     }
  24.     return res;
  25. }
  26. int main()
  27.  {
  28. int t;
  29. cin>>t;
  30. while(t--)
  31. {
  32.     int n;
  33.     cin>>n;
  34.     char a[n];
  35.     cin>>a;
  36.     int now = totalNumberOfWays(a,n);
  37.     cout<<now<<endl;
  38. }
  39. return 0;
  40. }


Here is the Video:

Comments