• ACM 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
    解题思路 1. 将右起第一个“01”,改变为“10” 2. 将该“01”后面的所有“1”移动至最后
    #include <iostream>
    #include <string>
    #include <bitset>
    #include <algorithm>
    using namespace std;
    
    int main(){
        int n;
        while(cin >> n){
            bitset<32> bitInt(n);
            string strInt =bitInt.to_string();
            int pos = strInt.rfind("01");
            swap(strInt[pos],strInt[pos+1]);
            if(pos+2 < 31) sort(strInt.begin()+pos+2,strInt.end());
            cout<<bitset<32>(strInt).to_ulong()<<endl;
        }
    }
    
    

     string rfind("01")从字符串右边找”01“然后返回”01“的位置

    将01后面的1移动到最后相当于对01后面的字符串排序



  • 相关阅读:
    mysql-community-server-5.7.24 & 5.7.31 (5.6.35 升级到 5.7.24)
    企业 数据 能力 中台 大数据平台 CRM
    Tomcat日志切割配置
    你不知道的 Blob
    细说websocket快速重连机制
    DNS反向查询
    从安全的角度看待DNS
    LVS 负载均衡集群
    Linux服务器配置DNS解析
    react修改state的值
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3675251.html
Copyright © 2020-2023  润新知