编程之美面试题2

题目:中国象棋将帅问题

思路:

遍历A的位置

遍历B的位置

判断A、B的位置组合是否满足要求。

如何满足,则输出。


方法1:使用了位与运算

方法2:使用循环,利用对数求余

方法3:使用了位域结构

关于位域:

// 位域的使用.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <memory.h>
#include <iostream>

using namespace std;
struct A
{
	int a:5;
	int b:3;
};

struct B
{
	int a:3;
	int b:2;
	int c:3;
};

struct C
{
	char a:8;
	char b:2;
	char c:3;
};

struct D
{
	int a:2;
	int :2;
	int b:3;
	int c:2;
};

struct E
{
	unsigned a:4;
	unsigned b:5;
	unsigned c:4;
};

int _tmain(int argc, _TCHAR* argv[])
{
	char str[100] = "0134324324afsadfsdlfjlsdjfl";
	struct A d;

	memcpy(&d, str, sizeof(A));
	cout << sizeof(A) << endl;  //4
	cout << sizeof(B) << endl;  //4
	cout << sizeof(C) << endl;  //1
	cout << sizeof(D) << endl;  //4/8/16
	cout << sizeof(E) << endl;  //4
	
	cout << d.a << endl;
	cout << d.b << endl;

	return 0;
}



一下给出了三个算法的代码:

// 面试题2.cpp : 定义控制台应用程序的入口点。
//

/*
*功能:中国象棋将帅问题
*时间:2014-6-23-21:49
*/
#include "stdafx.h"

#define HALF_BITS_LENGTH 4
//11111111
#define FULLMASK 255
//11110000
#define LMASK (FULLMASK << HALF_BITS_LENGTH)
//00001111
#define RMASK (FULLMASK >> HALF_BITS_LENGTH)

//这个宏,将b的右边设置成n
#define RSET(b,n) (b = ((LMASK & b) | (n)))
//这个宏,将b的左边设置成n
#define LSET(b,n) (b = ((RMASK & b) | ((n) << HALF_BITS_LENGTH)))

//这个宏得到b的右边的值
#define RGET(b) (RMASK & b)
//这个宏得到b的左边的值
#define LGET(b) ((LMASK & b) >> HALF_BITS_LENGTH)
//这个数字表示将帅移动范围的行宽度
#define GRIDW 3

//解法1:使用位与操作
void Solution_1()
{
	unsigned char b = 0xa5;
	for(LSET(b,1); LGET(b) <= GRIDW * GRIDW; LSET(b, (LGET(b) + 1)))
		for(RSET(b, 1); RGET(b) <= GRIDW * GRIDW; RSET(b, (RGET(b) + 1)))
			if(LGET(b) % GRIDW != RGET(b) % GRIDW)
				printf("A = %d, B = %d\n", LGET(b), RGET(b));
}

//解法2:
void Solution_2()
{
	unsigned char i = 81;
	while(i--)
	{
		if(i / 9 % 3 == i % 9 % 3)
			continue;
		printf("A = %d, B = %d\n", i / 9 + 1, i % 9 + 1);
	}
}

//解法3:
void Solution_3()
{
	//定义了一个无名位域结构体
	struct { //把一个字节中的二进位划分为几个不同的区域,并说明每个区域的位数
		unsigned char a:4;  //位域类型
		unsigned char b:4;
	}i;

	for(i.a = 1; i.a <= 9; i.a++)
	{
		for(i.b = 1; i.b <= 9; i.b++)
		{
			if(i.a % 3 != i.b % 3)
				printf("A = %d, B = %d\n", i.a, i.b);
		}
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	//Solution_2();
	Solution_3();

	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值