在一个多项式方程中合并相似项。

huangapple go评论75阅读模式
英文:

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 &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;map&gt;
 
int main()
{
	std::vector&lt;int&gt; nums{1, 2, 2, 4, 3, 6, 4, 2, 5, 4};
	std::map&lt;int, int&gt; exponent_occurences;
	for (unsigned int i = 1; i &lt; nums.size(); i += 2)
		exponent_occurences[nums.at(i)] += nums.at(i - 1);
	for (auto&amp; [exponent, coef]: exponent_occurences)
		std::cout &lt;&lt; coef &lt;&lt; &quot;x^&quot; &lt;&lt; exponent &lt;&lt; std::endl;
	return 0;
}

huangapple
  • 本文由 发表于 2020年10月9日 17:33:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/64277395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定