Utopian Tree in Java

The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the monsoon, when it doubles in height. The second growth cycle 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 <= 60

Output Format
For each test case, print the height of the Utopian tree after N cycles.

Sample Input #00:

2
0
1

Sample Output #00:

1
2

Explanation #00:
There are 2 test cases. When N = 0, the height of the tree remains unchanged. When N = 1, the tree doubles its height as it's planted just before the onset of monsoon.

Sample Input: #01:

2
3
4

Sample Output: #01:

6
7

Explanation: #01:
There are 2 testcases.
N = 3:
the height of the tree at the end of the 1st cycle = 2
the height of the tree at the end of the 2nd cycle = 3
the height of the tree at the end of the 3rd cycle = 6

N = 4:
the height of the tree at the end of the 4th cycle = 7

 

 

题目如上,乌托邦树,第一行输入是有几个test case,后面是每一个test case中树要长几轮

树如果长奇数轮就是每次在原基础上+1,偶数次轮数就是每次原基础*2,如果没有增长(n=0),那么树的初始高度为0.

所以题解就是简单的进行奇偶判断累加即可。

主要利用这道题复习java中如何使用scanner

 

代码如下:

复制代码
 1 import java.io.*;
 2 import java.util.*;
 3 import java.text.*;
 4 import java.math.*;
 5 import java.util.regex.*;
 6 
 7 public class Solution {
 8 
 9 
10     static int helper(int num) {
11         int i = 1;
12         int base = 1;
13         while(i<=num){
14             if(i%2==0){
15                 base = base+1;
16             }else{
17                 base = base*2;
18             }
19             i++;
20         }
21         return base;
22    }
23 
24    
25  public static void main(String[] args) {
26         Scanner in = new Scanner(System.in);
27         int t;
28         t = in.nextInt();
29         int [] n = new int[t];
30      
31         int i = 0;
32         while(in.hasNext()&&i<t){
33             n[i] = in.nextInt();
34             i++;
35         }
36      
37        int [] res = new int[t];
38        for(i = 0; i < t; i++)
39            res[i] = helper(n[i]);
40        
41        for(i = 0; i<res.length; i++)
42            System.out.println(res[i]);
43        
44        
45    }
46 }
复制代码

 

posted @   爱做饭的小莹子  阅读(861)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示