There is a strange counter. In the first second, it displays the number 3. Each second, the number displayed by decrements by 1 until it reaches 1. In the next second, the timer resets to (2x the initial number for the prior cycle) and continues counting down.
Find and print the value displayed by the counter at the time t.
Example:
Input: t=4
Output: 6
Approach
Java
public class StrangeCounter {public static void main(String[] args) {long t = 4;long result = strangeCounter(t);System.out.println(result);}private static long strangeCounter(long t) {long cnt = 3;while (t > cnt) {t = t - cnt;cnt = cnt * 2;}return cnt - t + 1;}}
C++
#include <bits/stdc++.h>using namespace std;long strangeCounter(long t){long cnt = 3;while (t > cnt){t = t - cnt;cnt = cnt * 2;}return cnt - t + 1;}int main(){long t = 4;long result = strangeCounter(t);cout << result << "\n";return 0;}
No comments:
Post a Comment