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 函数中,参数是传值,还是传引用?
    CSRF(Cross Site Request Forgery, 跨站域请求伪造)
    Django 中间件
    python的内存管理机制
    adb的一些常用的命令
    ant使用备忘
    关于如何以编程的方式执行TestNG
    关于使用testng的retry问题
    SSH中将hibernate托管给spring获取session的方法
  • 原文地址:https://www.cnblogs.com/hpuwangjunling/p/2381371.html
Copyright © 2011-2022 走看看