Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Thursday, August 3, 2017

Pattern till N


Problem :

Print a sequence of numbers starting with N, without using loop, in which  A[i+1] = A[i] - 5,  if  A[i]>0, else A[i+1]=A[i] + 5  repeat it until A[i]=N.

Code:

import java.util.*;
import java.lang.*;
import java.io.*;
class hackerranksolutionc
 {
     public static void show(int n,int cur,Stack<Integer> st)
     {
         if(cur<=0)
        {
             st.push(cur);
            return;}
         st.push(cur);
         System.out.print(cur+" ");
         show(n,cur-5,st);
     }
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
   int n=ab.nextInt();
   Stack<Integer> st=new Stack<Integer>();
   show(n,n,st);
   while(st.size()>0)
   System.out.print(st.pop()+" ");
    System.out.println();
}
}
}

0 Comments:

Post a Comment

Stats