Task: Find the all jumping numbers smaller than or equal to given X, Jumping number means a number all adjacent digits differ by 1.
Example:
Input:
1
50
Output:
0 1 2 3 4 5 6 7 8 9 10 12 21 23 32 34 43 45
Here is the Code:
Program in C++:
- #include<iostream>
- #include<bits/stdc++.h>
- using namespace std;
- void jumpingNumbers(int *jd,int n)
- {
- queue<int> q;
- jd[0]=0;
- int i;
- for(i=1;i<10;i++)
- {
- jd[i]=i;
- q.push(i);
- }
- int num;
- while(q.empty()==false&&i<=n)
- {
- num=q.front();
- int t1=num%10;
- if(t1==0)
- {
- jd[i++]=num*10+t1+1;
- q.push(jd[i-1]);
- }
- else if(t1==9)
- {
- jd[i++]=num*10+t1-1;
- q.push(jd[i-1]);
- }
- else
- {
- jd[i++]=num*10+t1-1;
- q.push(jd[i-1]);
- jd[i++]=num*10+t1+1;
- q.push(jd[i-1]);
- }
- q.pop();
- }
- }
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int n;
- cin>>n;
- int jd[3500];
- jumpingNumbers(jd,3501);
- int i=0;
- while(jd[i]<=n)
- {
- cout<<jd[i]<<" ";
- i++;
- }
- cout<<endl;
- }
- return 0;
- }
Here is the Video:
Comments
Post a Comment