zoukankan      html  css  js  c++  java
  • 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 }
    
    
  • 相关阅读:
    CodeIgniter(3.1.4)框架中成功/错误跳转
    CodeIgniter(3.1.4)框架-url重写,去除index.php
    CodeIgniter(3.1.4)框架中-使用多个公共控制器
    CodeIgniter(3.1.4)框架使用静态文件(js,css)
    PHP无限极分类
    PHP无限极分类
    spring中定时任务quartz2.2.3
    eclipse中git更新操作
    java中日期的换算处理
    使用spring-rabbit测试RabbitMQ消息确认(发送确认,接收确认)
  • 原文地址:https://www.cnblogs.com/wkfvawl/p/9383334.html
Copyright © 2011-2022 走看看