zoukankan      html  css  js  c++  java
  • Same binary weight

     

    Same binary weight

    时间限制:300 ms  |  内存限制:65535 KB
    难度:3
     
    描述

    The binary weight of a positive  integer is the number of 1's in its binary representation.for example,the decmial number 1 has a binary weight of 1,and the decimal number 1717 (which is 11010110101 in binary) has a binary weight of 7.Give a positive integer N,return the smallest integer greater than N that has the same binary weight as N.N will be between 1 and 1000000000,inclusive,the result is guaranteed to fit in a signed 32-bit interget.

     
    输入
    The input has multicases and each case contains a integer N.
    输出
    For each case,output the smallest integer greater than N that has the same binary weight as N.
    样例输入
    1717
    4
    7
    12
    555555
    样例输出
    1718
    8
    11
    17
    555557
    这道题的解,关键是求出n的二进制数最末位0和1的位数:

    #include<iostream>
    #include<cstdio>

    using namespace std;

    int main()
    {
      int n,i,n0,cnt1,cnt2,k,l,N;

      while(scanf("%d",&n)!=EOF)
      {
       cnt1=0;
       N=n;
       while(n)
       {
        if(n%2!=0)
         break;
          cnt1++;
        n/=2;
       }
       cnt2=cnt1;
       while(n)
       {
        if(n%2==0)
         break;
           cnt2++;
        n/=2;
       }
       k=l=1;
       for(i=1; i<=cnt1; i++)
        k*=2;
         k-=1;
       for(i=1; i<=cnt2-cnt1-1; i++)
        l*=2;
          n0=k+l;
       printf("%d\n",n0+N);
      }
      return 0;
    }

  • 相关阅读:
    事务/数据库操作之事务,开启回滚提交
    python连接数据库、cursor fetch语句处理
    order by 排序输出、插入
    表的查询,
    android权限大全
    uniapp ios端证书打包+开发环境
    uniapp在app端白屏报错
    数字递增动画js插件-countUp.js
    窗口滚动时,判断元素与视野的关系-js代码
    Linux安装Nginx并配置站点
  • 原文地址:https://www.cnblogs.com/hpuwangjunling/p/2381371.html
Copyright © 2011-2022 走看看