鏈接: http://acm.gdufe.edu.cn/PRoblem/read/id/1206
Problem Description:
long long ans = 0; for(int i = 1; i < = n; i ++) ans += lowbit(i) lowbit(i)的意思是將i轉(zhuǎn)化成二進制數(shù)之后,只保留最低位的1及其后面的0,截斷前面的內(nèi)容,然后再轉(zhuǎn)成10進制數(shù) 比如lowbit(7),7的二進制位是111,lowbit(7) = 1 6 = 110(2),lowbit(6) = 2,同理lowbit(4) = 4,lowbit(12) = 4,lowbit(2) = 2,lowbit(8) = 8
每輸入一個n,求ans Input:
多組數(shù)據(jù),每組數(shù)據(jù)一個n(1 <= n <= 5*10^8)
Output:
每組數(shù)據(jù)輸出一行,對應的ans Sample Input:
1 2 3 Sample Output:
1 3 4
首先, lowbit (i) = i&-i for(int i = 1; i < 100; i++) printf(“%d/n”, lowbit(i) ); 觀察其規(guī)律,可以發(fā)現(xiàn): i為 1,3,5,7,9…時,lowbit(i) == 1, i為 2,6,10,14,18…時,lowbit(i) == 2, i為 4,12,20,28,36…時,lowbit(i) == 4, i為 8,24,40,56,72…時,lowbit(i) == 8…
代碼:
#include <stdio.h>#include <math.h>int main(){ int n; while(scanf("%d", &n) == 1){ int p = (int)log2(n); long long ans = 0; for(int i = 0; i <= p; i++){ ans += ((n - (1 << i)) / (1 << (i+1)) + 1) * (1 << i);//懶得描述。。。反正根據(jù)規(guī)律可以推出來 } printf("%lld/n", ans); } return 0;}//需要注意:<<的優(yōu)先級比-低
|
新聞熱點
疑難解答