英文:
Combine like terms in a polynomial equation
问题
以下是您要求的翻译内容:
不是作业或其他什么,只是关于编程的个人兴趣,目前正在自学。
在网上发现了这个有趣的问题。
想象一下,如果我们有一个数字列表:
1 2 2 4 3 6 4 2 5 4
这相当于 1x^2+2^4+3^6+4^2+5^4
。
当具有相同指数的数字相同时,如何将它们结合在一起?
这将变成 5x^2+6x^4+3x^6
我认为我们可以在这种情况下使用链表?但我不太了解如何使用这种数据结构。
还有其他解决这种问题的方法吗?
最好用C++或Java示例。
英文:
Not homework or anything, just personal interests on coding, learning it by myself currently.
Found this question interesting online.
Think if we have a list of number that's
1 2 2 4 3 6 4 2 5 4
that equals to 1x^2+2^4+3^6+4^2+5^4
How can I combine the numbers when they have the same exponent?
which will become 5x^2+6x^4+3x^6
I think we can use a linked list in this case? But I don't really know use this data structure
Or anything other way to solve this kind of problem?
Prefer examples in C++ or Java
答案1
得分: 2
你可以这样做:
#include <iostream>
#include <vector>
#include <map>
int main()
{
std::vector<int> nums{1, 2, 2, 4, 3, 6, 4, 2, 5, 4};
std::map<int, int> exponent_occurences;
for (unsigned int i = 1; i < nums.size(); i += 2)
exponent_occurences[nums.at(i)] += nums.at(i - 1);
for (auto& [exponent, coef]: exponent_occurences)
std::cout << coef << "x^" << exponent << std::endl;
return 0;
}
英文:
You can do it like this:
#include <iostream>
#include <vector>
#include <map>
int main()
{
std::vector<int> nums{1, 2, 2, 4, 3, 6, 4, 2, 5, 4};
std::map<int, int> exponent_occurences;
for (unsigned int i = 1; i < nums.size(); i += 2)
exponent_occurences[nums.at(i)] += nums.at(i - 1);
for (auto& [exponent, coef]: exponent_occurences)
std::cout << coef << "x^" << exponent << std::endl;
return 0;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论