微策略笔试题

题目:序列123...N,N介于3和9之间,在其中加入+、-或者空格,使其和为0,

如123456  1-2 3-4 5+6 7 等价于1-23-45+67=0。请问,如何获得所有组合?使用递归和非递归。下面的代码是别人写的,个人认为很好就收藏了。

C++代码:

//序列123...N,N介于3和9之间,在其中加入+、-或者空格,使其和为0,
//如123456  1-2 3-4 5+6 7 等价于1-23-45+67=0。请问,如何获得所有组合?使用递归和非递归。
//非递归算法
#include <iostream>
#include <cmath>
using namespace std;

void func (char* str);
void calc (char* result);

int main()
{
	char str[] = "123456789";
	func(str);
	return 0;
}

void func(char* str)
{
	//初始化输出数组
	int len = strlen(str);
	char* result = new char[len*2];
	for (int i = 0; i < len; i++)
	{
		result[i*2] = str[i];
	}
	result[len*2-1] = '\0';
	
	//模拟3进制的运算
	char key[3] = {' ', '+', '-'};
	int n = pow(3.0, len - 1);
	for (int i = 0; i < n; i++)
	{
		//把i转换成3进制,计算每一位,转换成字符,填入字符串相应位置
		int pos = len * 2 - 3; //个位数填入位置
		int temp = i, mod;
		do
		{
			mod = temp % 3;
			temp /= 3;
			result[pos] = key[mod];
			pos -= 2;
		}while (temp > 0);
		//高位补0
		while (pos > 0)
		{
			result[pos] = key[0];
			pos -= 2;
		}
		calc(result);  //计算结果并输出
	}

	delete[] result;
}

void calc(char* result)
{
	int sum = 0, sign = 1, i = 0;
	int temp = 0;
	while (result[i] != '\0')
	{
		if (result[i] == ' ')
		{
			temp *= 10;
		}
		else if(result[i] == '+' || result[i] == '-')
		{
			sign = (result[i] == '+') ? 1 : -1;
			sum += temp;
			temp = 0;
		}
		else
		{
			temp += sign * (result[i] - '0');
		}
		i++;
	}
	sum += temp;
	if (sum == 0)
	{
		cout << result << endl;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值