首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【南理oj】412 - Same binary weight(STL - 双端队列 & 全排列)

【南理oj】412 - Same binary weight(STL - 双端队列 & 全排列)

作者头像
FishWang
发布2025-08-26 19:32:51
发布2025-08-26 19:32:51
8800
代码可运行
举报
运行总次数:0
代码可运行

点击打开题目

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. 样例输入

代码语言:javascript
代码运行次数:0
运行
复制
1717
4
7
12
555555

样例输出

代码语言:javascript
代码运行次数:0
运行
复制
1718
8
11
17
555557

来源 topcoder 上传者 骆魁永

用双端队列加全排列省时省力。

把其二进制列好后,在最前面加一个前导0,然后生成下一个全排列,然后转换为十进制输出即可。

代码如下:

代码语言:javascript
代码运行次数:0
运行
复制
#include <cstdio>
#include <deque>
#include <algorithm>
using namespace std;
int main()
{
	int n;
	int num;
	int ans;
	while (~scanf ("%d",&n))
	{
		deque<int> q;
		while (n)		//将数字的二进制存入双端队列 
		{
			q.push_front(n & 1);
			n >>= 1;
		}
		q.push_front(0);
		next_permutation(q.begin(),q.end());
		ans = 0;
		num = 0;
		while (!q.empty())
		{
			ans += (q.back() << num);
			num++;
			q.pop_back();
		}
		printf ("%d\n",ans);
	}
	return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Same binary weight
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档