보안 / 개발 챌린저가 목표

[AlphaGo Study] [HackerRank] [JAVA] Strange Counter 본문

Development/Algorithm

[AlphaGo Study] [HackerRank] [JAVA] Strange Counter

햄미은서 2020. 9. 17. 14:19

 

문제 설명

 Bob has a strange counter. At the first second, it displays the number 3. Each second, the number displayed by the counter decrements by 1 until it reaches 1.

 The couner counts down in cycles. In next second, the timer resets to 2 × the initial number for the prior cycle and continues counting down. The diagram below shows the counter values for each time t in the first three cycles:

 

Find and print the value displayed by the counter at time t.

제한 사항

  • Complete the strangeCounter function in the editor below. It should return the integer value displayed by the counter at time t.
  • strangeCounter has the following parameters(s):   ⇒ t: an integer
  • 1 ≤ t ≤ 10¹²
  • Subtask : 1 ≤ t ≤ 100000 for 60% of the maximum score.
  • Input Format : A single integer denoting the value of t.
  • Output Format : Print the value displayed by the strange counter at the given time t.

입출력 예

t result
4 6

입출력 예 설명

#예제

 Time t = 4 marks the beginning of the second cycle. It is double the number displayed at the beginning of the first cycle: 2 × 3 = 6. This is also shown in the diagram in the Problem Statement above.

 

https://www.hackerrank.com/challenges/strange-code/problem

 

Strange Counter | HackerRank

Print the value displayed by the counter at a given time, $t$.

www.hackerrank.com


문제를 풀기 전 THINK

  • value의 처음 값은 3이다.
  • value의 값이 1이 되면 다음 주기로 넘어간다.
  • 다음 주기의 처음 value 값 = 전 주기 처음 value × 2
  • value의 처음 값 = time의 처음 값 + 2

나의 Solution

public class StrangeCounter {
	long strangeCounter(long t) {
		long time_top = 1;
		long value_top = 3;
		
		// 각 주기의 맨 위의 값 구하기
		while(time_top <= t) {
			time_top += value_top;
			value_top = time_top + 2;
		}
		
		// 구하고 싶은 시간의 다음 주기 time_top에서 구하고 싶은 시간 빼면 됨
		return (time_top - t);
    }
}

 

Comments