美文网首页
Codeforces 1362C - Johnny and A

Codeforces 1362C - Johnny and A

作者: 费城的二鹏 | 来源:发表于2020-06-13 22:51 被阅读0次

日常一道算法题。

翻译

Johnny 和另一次排名下降

Johnny最喜欢的编程比赛平台的最后一次比赛广受好评,可是他的排名再次下降了。他觉着这个比赛任务虽然很友爱,但是并不能真正的展示出比赛者的技能水平。

这个男孩在一个二进制系统查看排名。他觉着从 0 到 n 这 n + 1 个二进制数字,相邻数字的二进制相差个数的位数和,决定了这场比赛的不公平性。

想要求出这个数字的总和。

输入格式

输入整数 t 表示测试用例组数。

每个测试用例输入一个整数 n。

输出格式

输出不公平数字。

分析

一道找规律的题目。

0 0 => 2^0 - 1
1 1 => 2^1 - 1
2 3 => 2^2 - 1
4 7 => 2^3 - 1
8 15 => 2^4 - 1
...

然后就是按位取1,找到1 就用公式计算出数字,然后求和。

代码(Python3)

# https://codeforces.com/problemset/problem/1362/C
 
import sys
import os
import heapq
import math
 
try:
    path = "./file/input.txt"
    if os.path.exists(path):
        sys.stdin = open(path, 'r')
    # sys.stdout = open(r"./file/output.txt", 'w')
except:
    pass
 
t = int(input())
 
def printd(value):
    # print(value)
    pass
 
def case():
    n = int(input())
    bit = 1
    result = 0
    while n > 0:
        if n & 1 == 1:
            result += 2**bit - 1
        bit += 1
        n = n >> 1
    print(result)

for _ in range(t):
    case()

更多代码尽在 https://github.com/Tconan99/Codeforces

by 费城的二鹏 2020.06.11 长春

相关文章

网友评论

      本文标题:Codeforces 1362C - Johnny and A

      本文链接:https://www.haomeiwen.com/subject/uhobtktx.html