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后面的字符串排序



posted @   OpenSoucre  阅读(211)  评论(1编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示