Simple algorithm based HackerRank challenge.
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle of the tree occurs during the monsoon, when it doubles in height. The second growth cycle of the tree occurs during the summer, when its height increases by 1 meter. Now, a new Utopian tree sapling is planted at the onset of the monsoon. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
Input Format
The first line contains an integer, T, the number of test cases. T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case.Constraints
1 <= T <= 10 0 <= N <= 60Output Format
For each test case, print the height of the Utopian tree after N cycles.
Test Cases can be found at HackerRank
static int[] LifeCycle(int[] input)
{
int[] output = new int[input.Length];
for (int i = 0; i < input.Length; i++)
{
int lifeCycleCount = Convert.ToInt32(input[i]);
if (lifeCycleCount == 0)
{
output[i] = 1; //no growth
}
else
{
var treeHeight = 1;
for (int j = 0; j < input[i]; j ++)
{
if (j % 2 == 0)
{
treeHeight = treeHeight + treeHeight; //Monsoon Growth
}
else
{
treeHeight++; //Summer Growth
}
}
output[i] = treeHeight;
}
}
return output;
}
static void Main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
int howMany = Convert.ToInt32(Console.ReadLine());
int[] input = new int[howMany];
for (int i = 0; i < howMany; i++)
{
input[i] = Convert.ToInt32(Console.ReadLine());
}
int[] result = LifeCycle(input);
for (int i = 0; i < result.Length; i++)
{
Console.WriteLine(result[i].ToString());
}
}
Simple enough, but do I really need to use all the if statements and for loops?
I passed all the tests they put the code through (0.08s on each, total of 9 tests)