1. 程式人生 > 其它 >牛客 XOR和(找規律)

牛客 XOR和(找規律)

技術標籤:LintCode及其他OJ

文章目錄

1. 題目

連結:https://ac.nowcoder.com/acm/contest/10166/C
來源:牛客網

牛牛最近學會了異或操作,於是他發現了一個函式 f ( x ) = x ⊕ ( x − 1 ) f(x)=x\oplus (x-1) f(x)=x(x1),現在牛牛給你一個數 n,他想知道 ∑ i = 1 n f ( i ) \sum_{i=1}^n f(i) i=1nf(i) 的值是多少,請你告訴他。

示例1
輸入
4
返回值
12
備註:
1≤n≤10^9

2. 解題

先算出 10 以內的 f(x)

i      f(i)      S(i)
1      1         1      
2      3         4       
3      1         5       
4      7        12       
5      1        13       
6      3        16       
7      1        17       
8     15        32    

發現x奇數時, f ( x ) = 1 f(x) = 1 f(x)=1;
x偶數時, f ( x ) = 2 ∗ f ( x / 2 ) + 1 f(x) = 2*f(x/2)+1

f(x)=2f(x/2)+1
S u m ( n ) = n + 2 ∗ S u m ( n / 2 ) ; Sum(n) = n+2*Sum(n/2); Sum(n)=n+2Sum(n/2);

class Solution {
public:
    /**
     * 程式碼中的類名、方法名、引數名已經指定,請勿修改,直接返回方法規定的值即可
     * 
     * @param n int整型 
     * @return long長整型
     */
    unordered_map<int, long long> m;
    long long Sum(int n)
{ // write code here if(n == 1) return 1; if(m.find(n) != m.end()) return m[n]; long long s = n+2*Sum(n/2); return m[n] = s; } };

我的CSDN部落格地址 https://michael.blog.csdn.net/

長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
Michael阿明