Utopian Tree

The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter.

A Utopian Tree sapling with a height of 1 meter is planted at the onset of spring. How tall will the tree be after n growth cycles?


Example:

Input:  n=4
Output: 7

Approach

Java

public class UtopianTree {
    public static void main(String[] args) {
        int n = 4;
        System.out.println(utopianTree(n));
    }

    private static int utopianTree(int n) {
        int h = 1;
        if (n == 0) {
            return h;
        } else {
            for (int j = 1; j <= n; j++) {
                if (j % 2 == 1)
                    h = h * 2;
                else
                    h = h + 1;
            }
            return h;
        }
    }
}


C++

#include <bits/stdc++.h>
using namespace std;

int utopianTree(int n)
{
    int h = 1;
    if (n == 0)
    {
        return h;
    }
    else
    {
        for (int j = 1j <= nj++)
        {
            if (j & 1)
                h = h * 2;
            else
                h = h + 1;
        }
        return h;
    }
}

int main()
{

    int n = 4;
    cout << utopianTree(n);
    return 0;
}


No comments:

Post a Comment