2020 Updated Utopian Tree Hackerrank solution in c++

Coding Demons has solved Utopian Tree a problem on Hackerrank. The Solution is given in two stages.

Stage 1 Logic

Stage 2 Code



For better understanding refer our YouTube Tutorial Video.


LOGIC 
  • Input no. of test cases
  • For each test case set height to 1
  • For 0th period print 1.
  • For even period increment height by 1.
  • For odd period double the height.
  • Print the height.


CODE

/*** SOLUTION BY CODING DEMONS ***/

#include <bits/stdc++.h>
using namespace std;
int main () {

    int n;
    cin>>n;     //no of test cases

 for (int i=0;i<n;i++){
     int a=1;       //set height to 1
     int x;        // input period
     cin>>x;

     if (x==0){         //for 0th cycle
        cout<<a<<endl;
     }
     else {
     for (int j=1;j<=x;j++){

//for even period increment by 1 (summer)
         if (j%2==0){      
             a=a+1;
         }

 //for odd period double the height (spring)
         else {
             a=a*2;      
         }
      }
      cout<<a<<endl;   //print height
     }
    }
}    

/*** END ***/




!! FOLLOW FOR CODES & VIDEOS !!

    Post a Comment

    0 Comments