Sort by

recency

|

992 Discussions

|

  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/Plsx1i8dqiI

    long strangeCounter(long t) {
        long last = 3, step = 3;
        while(t > last){
            step *= 2;
            last += step;
        }
        return last - t + 1;
    }
    
  • + 0 comments

    ini solusi tanpa looping, dengan merumuskan masalah menjadi sebuah pola

        public static long strangeCounter(long t)
        {
            // 1, 4, 10, 22, 46 .... Un
            // 1 + (3* (2^0 - 1) => 1
            // 1 + (3* (2^1 - 1) => 4
            // 1 + (3* (2^2 - 1) => 10
            // 1 + (3* (2^3 - 1) => 22
            // 1 + (3* (2^4 - 1) => 46
            // 1 + (3* (2^5 - 1) => 94
            // ...
            // 1 + (3* (2^n - 1) => formula for the n-th term
    
            // how to get n from (2^n - 1), log2 (floor(time+2)/2)
            long n = (int)Math.Floor(Math.Log((t+2) / 3, 2));
            
            long topValue = long.Parse((3 * Math.Pow(2, n)).ToString());
            long topTime = topValue - 2;
    
            return topValue - (t - topTime);
        }
    
  • + 0 comments

    Here is my Python code!

    def strangeCounter(t):
        time = 1
        value = 3
        while time + value <= t:
            time += value
            value = 2 * value
        return value - (t - time)
    
  • + 0 comments

    The problem can be solved in O(1) If f(t) == 1, t = sum of geometric progression an = 3*2(n-1) . So we can find the next t where f(t) == 1

  • + 0 comments
    long strangeCounter(long t) {
        long sum =3, counter = 3;
        while(sum < t){
            counter = counter*2;
            sum += counter;
        }
        
        return sum - t + 1;
    }