在多项式方程中合并相似项

问题描述

不是家庭作业或其他任何东西,只是个人兴趣编码,目前自己学习。 在网上发现了这个问题很有趣。

想想我们是否有一个数字列表

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的首选示例

解决方法

您可以这样做:

#include <iostream>
#include <vector>
#include <map>
 
int main()
{
    std::vector<int> nums{1,2,4,3,6,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;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...