// 智力题测试.cpp : 定义控制台应用程序的入口点。
//
/*
c语言编程 有5个砝码 分别是1,3,9,27,81 可以组合成1–121之间任意整数
对于用户给定的重量给出方案 如:输入5输出9-3-1
*/
#include “stdafx.h”
#include <stdio.h>
const int weight[5] = {1, 3, 9, 27, 81};
const int weight_sum[5] = {1, 4, 13, 40, 121};
const char operator_char[2] = {‘+’, ‘-‘};
int func(int num, int index, int *key)
{
int gap = 0;
if(num > weight[4])
{
printf(“%d+”, weight[4]);
num -= weight[4];
}
for(int i = 0; i < index; i++)
{
if(num <= weight[i])
{
index = i;
break;
}
}
gap = weight[index] – num;
/*
* 用了递归的方法
* grap > 前几个数的和 num就是前面一个数加 新的num
* <= 前几个数的和 num 就是weight[index] 减新的num
*
*/
if(gap > weight_sum[index -1])//+
{
index -= 1;
num = num – weight[index];
printf(“%d%c”, weight[index], operator_char[0+*key]);
}
if(gap <= weight_sum[index]) // –
{
num = weight[index] – num;
printf(“%d%c”, weight[index], operator_char[1-*key]);
*key = 1^*key;
/*
* 如果前面出现 – 後面的运算符 要变换如
* 5 = 9 – (3 + 1) => 5 = 9 – 3 – 1
* key 为控制运算变换的控制变量
*/
}
if(num == 0) return 0;
return func(num, index, key);
}
void main()
{
int pressKey;
int num, key, index;
while(1)
{
key = 0;
index = 5;
scanf(“%d”, &num);
num = num > 121?121:num;
num = num < 1?1:num;
printf(“%d = “, num);
func(num, index, &key);
printf(“\b \n”);
}
}