Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert this JavaScript code to C++

Problem is to return any one combination from given array that sums up to the target. I'm new to C++. How can I complete the function howSum() below? I can't return null here since the return type is vector. Also I'm having trouble passing the vectors.

JavaScript:

const howSum = (targetSum, numbers) => {
    if (targetSum === 0) return [];
    if (targetSum < 0) return null;

    for (let num of numbers) {
        const remainder = targetSum - num;
        const remainderResult = howSum(remainder, numbers);
        if (remainderResult !== null) 
        {
            return [...remainderResult, num];
        }
    }
    return null;
};

C++:

vector<int> howSum(int targetSum, vector<int> numbers)
{
    if(targetSum == 0) return {};
    if(targetSum < 0) return; //can't return null here in C++
    for (int i = 0; i < numbers.size(); i++)
    {
        int remainder = targetSum - numbers[i];
        vector<int> remainderResult = howSum(remainder, numbers);
        if(pass)
        {
            pass
        }
    }
}
like image 704
Display Smoker Avatar asked Jun 14 '26 18:06

Display Smoker


1 Answers

You can use C++17 std::optional and return std::nullopt when it does not contain value.

#include <optional>
#include <vector>

std::optional<std::vector<int>> 
howSum(int targetSum, const std::vector<int>& numbers) {
  if (targetSum == 0) 
    return std::vector<int>{};
  if (targetSum < 0) 
    return std::nullopt;
  for (auto numer : numbers) {
    const auto remainder = targetSum - numer;
    auto remainderResult = howSum(remainder, numbers);
    if (remainderResult) {
      remainderResult->push_back(targetSum);
      return remainderResult;
    }
  }
  return std::nullopt;
}
like image 144
康桓瑋 Avatar answered Jun 17 '26 11:06

康桓瑋



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!