Skip to content

Instantly share code, notes, and snippets.

@brunodrugowick
Created April 18, 2019 05:53
Show Gist options
  • Save brunodrugowick/7c1e1a48e9290b2d6765beb23deff467 to your computer and use it in GitHub Desktop.
Save brunodrugowick/7c1e1a48e9290b2d6765beb23deff467 to your computer and use it in GitHub Desktop.
A solution to Utopian Tree (hackerrank) in Java 8
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the utopianTree function below.
static int utopianTree(int n) {
if (n == 0) return 1;
if (n%2 == 0) return utopianTree(n-1) + 1;
else return utopianTree(n-1) * 2;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int t = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int tItr = 0; tItr < t; tItr++) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int result = utopianTree(n);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
}
bufferedWriter.close();
scanner.close();
}
}
@brunodrugowick
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment