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();
}
}
}
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