• Flip the Bits(思维)


    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
    ",count);
    31     }
    32     return 0;
    33 }
    
    
  • 相关阅读:
    推荐一个wpf&sliverlight的图表控件
    数独求解
    WPF中的 CollectionChanged事件通知
    Windows 7 任务栏之缩略图预览(Thumbnail)
    把Google HK设为IE默认的搜索引擎
    F#小记——1. Hello F#
    F#小记——2. 基本数据类型
    使用异步socket的时候需要注意memory spike
    《everytime you kissed me》的中文歌词
    我回来了o(∩_∩)o...
  • 原文地址:https://www.cnblogs.com/wkfvawl/p/9383334.html
Copyright © 2020-2023  润新知