Strange Counter – HackerRank Solution

In this post, we will solve Strange Counter HackerRank Solution. This problem (Strange Counter) is a part of HackerRank Databases series.

Task

There is a strange counter. At the first second, it displays the number 3. Each second, the number displayed by decrements by 1 until it reaches 1. In next second, the timer resets to 2 x 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.

Function Description

Complete the strangeCounter function in the editor below.

strangeCounter has the following parameter(s):

  • int t: an integer

Returns

  • int: the value displayed at time t

Input Format

A single integer, the value of t.

Constraints

  • 1 <= t <= 1012

Subtask

  • 1 <= t <= 105 for 60% of the maximum score.

Sample Input

4

Sample Output

6

Explanation

Time t = 4 marks the beginning of the second cycle. It is double the number displayed at the beginning of the first cycle: 2 x 3 = 6. This is shown in the diagram in the problem statement.

Solution – Strange Counter – HackerRank Solution

C++

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    long long cnt = 3;
    long long x;
    cin >> x;
    
    while(x > cnt) {
        x -= cnt;
        cnt *= 2;
    }
    
    cout << cnt - x + 1 << endl;
    
    return 0;
}

Python

import os
import sys
import math

#
# Complete the strangeCounter function below.
#
def strangeCounter(t):
    base = math.log2((t + 2)/3)
    val_top = 3*2**(math.floor(base))
    print("base = {} base_t = {}".format(base, val_top))
    
    return val_top - (t - (val_top-2))

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input())

    result = strangeCounter(t)

    fptr.write(str(result) + '\n')

    fptr.close()

Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

public class A {
    
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();
        PrintWriter out = new PrintWriter(System.out);
        long t = sc.nextLong();
        long cur = 0;
        long nxt = 3;
        while (cur < t) {
            cur += nxt;
            nxt <<= 1;
        }
        long val = 1;
        long dif = cur - t;
        val += dif;
        
        out.print(val);
        out.flush();
        out.close();
    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream s) {
            br = new BufferedReader(new InputStreamReader(s));
        }

        public String next() throws IOException {
            while (st == null || !st.hasMoreTokens())
                st = new StringTokenizer(br.readLine());
            return st.nextToken();
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public String nextLine() throws IOException {
            return br.readLine();
        }

        public double nextDouble() throws IOException {
            String x = next();
            StringBuilder sb = new StringBuilder("0");
            double res = 0, f = 1;
            boolean dec = false, neg = false;
            int start = 0;
            if (x.charAt(0) == '-') {
                neg = true;
                start++;
            }
            for (int i = start; i < x.length(); i++)
                if (x.charAt(i) == '.') {
                    res = Long.parseLong(sb.toString());
                    sb = new StringBuilder("0");
                    dec = true;
                } else {
                    sb.append(x.charAt(i));
                    if (dec)
                        f *= 10;
                }
            res += Long.parseLong(sb.toString()) / f;
            return res * (neg ? -1 : 1);
        }

        public boolean ready() throws IOException {
            return br.ready();
        }

    }
}

Note: This problem (Strange Counter) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *