1. 程式人生 > >Flip the Bits(思維)

Flip the Bits(思維)

style desc %d 後來 urn 個數 and nim possible

You are given a positive integer n. Your task is to build a number m by flipping the minimum number of bits in the binary representation of n such that m is less than n (m < n) and it is as maximal as possible. Can you?

Input

The first line contains an integer T (1 ≤ T

 ≤ 105) specifying the number of test cases.

Each test case consists of a single line containing one integer n (1 ≤ n ≤ 109), as described in the statement above.

Output

For each test case, print a single line containing the minimum number of bits you need to flip in the binary representation of n

to build the number m.

Example Input
2
5
10
Output
1
2


題目意思:將一個2進制的n中每個位翻轉得到一個比n小且盡可能大的數,求輸出翻轉了幾位。

解題思路:這道題該由我背鍋,我當時先是翻譯錯了題意,後來稍微有一點眉目了,我又理解錯了那個flip的意思,這裏面的翻轉並不是那種交換(swap那樣的),而是像硬幣正面換到反面那樣的翻轉,也就
是0與1的交換,根據題意可以推出想要得到一個既要比n小還有盡可能大的數,只有是n前面的那一個數n-1。所以就是根據n構造一個二進制的n-1,方法就是找到n的二進制中最後面的那一個1翻轉為0,而最
後一個1之後的0全都翻轉成1,統計所用的翻轉次數即可。

 1 #include<cstdio>
 2 #include<cstring>
 3 int main()
 4 {
 5     int t,n,j,k,i,count;
 6     int a[32];
 7     scanf("%d",&t);
 8     while(t--)
 9     {
10         scanf("%d",&n);
11         memset(a,-1,sizeof(a));
12         j=0;
13         count=0;
14         i=n;
15         while(i)
16         {
17             a[j]=i%2;
18             if(a[j]==0)
19             {
20                 count++;
21             }
22              if(a[j]==1)
23              {
24                  count++;
25                  break;
26              }
27             i/=2;
28             j++;
29         }
30         printf("%d\n",count);
31     }
32     return 0;
33 }





Flip the Bits(思維)