[每日练习]Amazon面试题---给定数组,求出运算符使得结果等于某个数



Question:

Given an array with positive integers and another integer for example{7 2 4} 9, you are required to generate an equation, by inserting operator add ("+") and minus ("-") among the array . The left side of equation are consist of the array and the right side of equation is the integer. here the result is 7-2+4=9

 

Rules:

Don't include any space in the generated equation.
In case there is no way to create the equation, please output "Invalid". For example {1 1} 10, output is "Invalid"
The length of the integer array is from 1 to 15( include 1 and 15). If the length is 1, for example the input  {7} 7, the output is 7=7
There is no operator "+" or "-" in front of the first number:
Don't change the order of the numbers. For example:  {7 2 4}  9. 7-2+4=9 is correct answer, 4-2+7=9 is wrong answer.
There could be multiple input, meaning your function could be called multiple times. Do remember print a new line after the call. 

Sample Input and Output:

Input:

1 2 3 4 10

1 2 3 4 5

Output:

1+2+3+4=10

Invalid


Solution:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void judge(int sum1, int *arr, char *op, int idx, int n, int sum2)
{
 if(idx == n)
 {
  if(sum1 == sum2)
  {
   int i=0;
   printf("%d", arr[0]);
   for(i=1; i<n; i++)
   {
    printf("%c%d", op[i], arr[i]);
   }
   printf("=%d\n", sum2);
  }
  return;
 }
 op[idx] = '+';
 judge(sum1+arr[idx], arr, op, idx+1, n, sum2);

 op[idx] = '-';
 judge(sum1-arr[idx], arr, op, idx+1, n, sum2);
}
static void ArraySum(int *arr, int n, int sum)
{
 char *op = (char *)malloc(n);
 memset(op, '+', n);
 judge(arr[0], arr, op, 1, n, sum);
 free(op);
}

int main()
{
 int arr[] = {1,2,3,4};
 ArraySum(arr, 4, 5);
 return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值