Strange Counter

一道算法题:
原题地址

Bob has a strange counter. At the first second,t=1 , it displays the number 3. At each subsequent second, the number displayed by the counter decrements by 1.

The counter counts down in cycles. In the second after the counter counts down to 1, the number becomes 2X the initial number for that countdown cycle and then continues counting down from the new initial number in a new cycle. The diagram below shows the counter values for each time t in the first three cycles:

  • 下面的代码结果正确,却是最笨的方法,所以时间上出现了超时,没有得到满分。

c语言代码


int main(){
    int t;
     int sum = 3;
     int j = 2;
    cin >> t;
   
    int bottom = 0;
     for( int i = 1 ; ; i++ ) {
            if( t <= sum ) {
                bottom = sum;
           break;
            }
            sum += j * 3;
            j *= 2;
     }
    cout<<bottom-t+1;
    return 0;
}


但是看过大神的讲解后,自己推倒了一遍公式总算写出来了


function main(t) {
    var t = parseInt(readLine());
    var n = Math.floor(Math.log((t-1)/3+1)/Math.log(2));
    var topValue = 3 * Math.pow(2,n);
    var topTime = topValue - 2;
    var value = topValue - ( t - topTime );
   
    console.log(value);
}


这道题的关键代码就是


var n = Math.floor(Math.log((t-1)/3+1)/Math.log(2));

因为Math.log()是以e为底的对数公式,所以要进行公式变化。

其中n代表所在列的index,从零开始。

我们可以利用等比序列的求和公式得出每一列的第一个time的值是


3*(2^n-1)+1  (n从零开始。)      

我们假设 time t 在列 n 中。


3*(2^n)+1 = t; 

log2((t-1)/3+1) = n   

n向下取整,就是当前所在列的index

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,134评论 0 23
  • 今天的我,忙运动会彩排,忙见师大过来看望我们的老师,忙着吃饭,忙着睡觉,忙着和同学们训练入场式,忙着制作运动会用的...
    鹿和绿色阅读 150评论 0 1
  • 再次在梦中悲伤地醒过来,有些怔怔,也有些明白…… 原来不是你留恋一个人,只不过习惯了用那种方式去证明自己的存在感!...
    阳光洒洒阅读 123评论 2 0
  • 《金文诚<孟子>学习笔记312,8-18-2,离娄章句下18-2》 【“苟为无本,七八月之间雨集,沟浍皆盈,其涸也...
    金吾生阅读 284评论 0 0
  • 我想说二次元,感谢一路上有你。 因为是你,把我从孤独救出去 因为是你,让原来没心没肺的我,学会哭,学会笑 因为是你...
    失落Forgotten阅读 177评论 1 3