Problem
HackerLand Enterprise is adopting a new viral advertising strategy. When they launch a new product, they advertise it to exactly people on social media.
On the first day, half of those people (i.e., ) like the advertisement and each shares it with of their friends. At the beginning of the second day, people receive the advertisement.
Each day, of the recipients like the advertisement and will share it with friends on the following day. Assuming nobody receives the advertisement twice, determine how many people have liked the ad by the end of a given day, beginning with launch day as day .
For example, assume you want to know how many have liked the ad by the end of the day.
Day Shared Liked Cumulative
1 5 2 2
2 6 3 5
3 9 4 9
4 12 6 15
5 18 9 24
The cumulative number of likes is .
Function Description
Complete the viralAdvertising function in the editor below. It should return the cumulative number of people who have liked the ad at a given time.
viralAdvertising has the following parameter(s):
- n: the integer number of days
Input Format
A single integer, , denoting a number of days.
Constraints
Output Format
Print the number of people who liked the advertisement during the first days.
Sample Input
3
Sample Output
9
Explanation
This example is depicted in the following diagram:
people liked the advertisement on the first day, people liked the advertisement on the second day and people liked the advertisement on the third day, so the answer is .
How I solved the problem
# Math.floor는 double을 반환함. 따라서 int로 강제 형변환을 해줘야함!
# 조건들을 보면서 코드를 짜면 짤 수 있을듯!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 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 viralAdvertising function below. static int viralAdvertising(int n) { int numberOfPeople = 5; int culmulative = 0; for (int i = 0; i < n; i++) { int halfOfPeople = (int)Math.floor(numberOfPeople / 2); culmulative += halfOfPeople; numberOfPeople = halfOfPeople * 3; } return culmulative; } 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 n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int result = viralAdvertising(n); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedWriter.close(); scanner.close(); } } | cs |
[출처 : https://www.hackerrank.com ]
'1 Day 1 Algorithms' 카테고리의 다른 글
[2019.03.11] Circular Array Rotation (0) | 2019.03.11 |
---|---|
[2019.03.07] Save the Prisoner! (0) | 2019.03.07 |
[2019.03.05] Beautiful Days at the Movies (0) | 2019.03.05 |
[2019.03.04] Angry Professor (0) | 2019.03.04 |
[2019.02.28] Utopian Tree (0) | 2019.02.28 |
댓글