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++:
- #include<iostream>
- using namespace std;
- int totalNumberOfWays(char *a,int n)
- {
- if(isalpha(n)) return 1;
- if(a[0]=='0') return 0;
- int p=1,q=1,res=1;
- for(int i=1;i<n;i++)
- {
- int t = (a[i-1]-'0')*10+a[i]-'0';
- if(t>=10&&t<=26)
- {
- if(t==10||t==20) res=p;
- else res=p+q;
- }
- else
- {
- if(t%10==0) return 0;
- else res=q;
- }
- p=q;
- q=res;
- }
- return res;
- }
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int n;
- cin>>n;
- char a[n];
- cin>>a;
- int now = totalNumberOfWays(a,n);
- cout<<now<<endl;
- }
- return 0;
- }
Here is the Video:
Comments
Post a Comment