UVA 12447-两个二进制只有一位不一样


D - Pieces and Bits
Time Limit:1000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu

Description

Download as PDF

Problem D: Pieces and Bits

Given an even integer N, print a sequence of 2^N different N-bit binary numbers in such way that every element of the sequence (except the first one) has exactly one bit the same as the previous one (e.g. 0001 and 1111)

Input Format

The input starts with an integer T - the number of test cases (T <= 8). T cases follow on each subsequent line, each of them containing the integer N (2 <= N <= 16).

Output Format

For each test case, print a sequence that satisfies the stated condition, one integer per line. Any valid sequence will be accepted.

Sample Input

1
2

Sample Output

0
1
3
2
(The sequence in the sample output in binary is {00,01,11,10})


求(1<<n)个二进制数和前面的只有一位不一样



自己写的代码:

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <set>
#include <map>
#include <string>
#include <string.h>

using namespace std;

int a[55];
int b[55];
int n;
int ans = 0;

void init () {
	memset (a, 0, sizeof (a));
	memset (b, 0, sizeof (b));
}

void change_to_twobinary (int x) {
	int k = 0;
	for (int j = 0; j < n; j++) {
		a[k++] = x % 2;
		x >>= 1;
	} 
}

int get_to_twobinary () {
	int ans = 0;
	for (int j = 0; j < n ; j ++) {
		ans = 2 * ans + b[j] ;
	}
	return ans;
}

int main() {
	int cas;
	scanf ("%d", &cas);
	while (cas--) {
		scanf ("%d", &n);
		int num = (1 << n);
		for (int i = 0; i < num; i++) {
			init ();
			int flag = i ;
			change_to_twobinary(flag);
			b[n - 1] = a[n - 1];
			for (int j = n - 2; j >= 0; j--) {
				if (a[j] != a[j + 1])  b[j] = 1;
				else  b[j] = 0;
			}
			if (!(i % 2)) {
				for (int j = 0; j < n; j++) {
					if (b[j] == 0) b[j] = 1;
					else b[j] = 0;
				}
			}
			printf("%d\n" , get_to_twobinary());
		}
	}
	return 0;
}

写的有点麻烦,没有直接简单的处理:

#include <iostream>
#include <cstdio>
using namespace std;

int N;

void solve() {
	N = 1 << N;
	for (int i = 0; i < N; i++) {
		if (i & 1) {
			int a = i >> 1;
			int b = i;
			int c = a ^ b;
			printf("%d\n", c ^ (N - 1));
		} else { 
			int a = i >> 1;
			int b = i;
			int c = a ^ b;
			printf("%d\n", c);
		}
	}
}

int main() {
	int T;
	scanf("%d", &T);
	while (T-- > 0) {
		scanf("%d", &N);
		solve();
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值