HyperText Markup Man
HyperText Markup Man

Reputation: 13

Converting Vector Arrays to Numbers

I created a function that converts numbers to arrays in C++. Due to this creation, I also created the opposite which converts arrays back to numbers:

int convertToNumber(vector<int> nums) {

    int length{ nums.size() };
    int Pow{ length - 1 };
    int factor{ pow(10, Pow) };
    int tempNum{};
    int result_num{};

    for (auto n : nums) {

        tempNum = n;
        tempNum *= factor;
        result_num += tempNum;
        Pow--;

    }

    return result_num;
}

Here is the issue. When I run this using the following code in main:

int main() {

  vector<int> nums {2, 3, 5, 6, 2, 6};

  int number = convertToNumber(nums);

  cout << number << endl;

}

I get 2,400,000 when I should be getting 235,626. I searched for a long time could not find the logic error within the code. Does somebody know what's going on?

Upvotes: 0

Views: 49

Answers (2)

JHBonarius
JHBonarius

Reputation: 11271

KIS (keep it simple)

int convertToNumber(std::vector<int> const& nums) {
    int result_num{0};
    for (auto n : nums) {
        result_num *= 10;
        result_num += n;
    }
    return result_num;
}

or even use an algorithm

int convertToNumber(std::vector<int> const& nums) {
    return std::accumulate(cbegin(nums), cend(nums), 0,
        [](int a, int n) { return a*10+n; });
}

Upvotes: 2

einpoklum
einpoklum

Reputation: 131546

With every iteration of your loop, you are updating Pow - but not factor; and it is factor that's used in your loop, not Pow.

Remember that when you assign an expression to a variable, that expression is only evaluated once, and the result of this single evaluation is what the variable is set to. In other words, the pow() function is not called each time you use factor; it's only called once with the initial value of Pow.

Note the code you provided would not compile. You must specify the namespace before identifiers such as vector and pow - they will not be understood by the compiler otherwise; and you will also need to include the appropriate headers.

If, by chance, you had a using namespace std hiding somewhere in your program - well, don't use that:

Why is "using namespace std;" considered bad practice?

Upvotes: 3

Related Questions