返回介绍

solution / 2100-2199 / 2118.Build the Equation / README_EN

发布于 2024-06-17 01:03:09 字数 3717 浏览 0 评论 0 收藏 0

2118. Build the Equation

中文文档

Description

Table: Terms

+-------------+------+
| Column Name | Type |
+-------------+------+
| power     | int  |
| factor    | int  |
+-------------+------+
power is the column with unique values for this table.
Each row of this table contains information about one term of the equation.
power is an integer in the range [0, 100].
factor is an integer in the range [-100, 100] and cannot be zero.

 

You have a very powerful program that can solve any equation of one variable in the world. The equation passed to the program must be formatted as follows:

  • The left-hand side (LHS) should contain all the terms.
  • The right-hand side (RHS) should be zero.
  • Each term of the LHS should follow the format "<sign><fact>X^<pow>" where:
    • <sign> is either "+" or "-".
    • <fact> is the absolute value of the factor.
    • <pow> is the value of the power.
  • If the power is 1, do not add "^<pow>".
    • For example, if power = 1 and factor = 3, the term will be "+3X".
  • If the power is 0, add neither "X" nor "^<pow>".
    • For example, if power = 0 and factor = -3, the term will be "-3".
  • The powers in the LHS should be sorted in descending order.

Write a solution to build the equation.

The result format is in the following example.

 

Example 1:

Input: 
Terms table:
+-------+--------+
| power | factor |
+-------+--------+
| 2   | 1    |
| 1   | -4   |
| 0   | 2    |
+-------+--------+
Output: 
+--------------+
| equation   |
+--------------+
| +1X^2-4X+2=0 |
+--------------+

Example 2:

Input: 
Terms table:
+-------+--------+
| power | factor |
+-------+--------+
| 4   | -4   |
| 2   | 1    |
| 1   | -1   |
+-------+--------+
Output: 
+-----------------+
| equation    |
+-----------------+
| -4X^4+1X^2-1X=0 |
+-----------------+

 

Follow up: What will be changed in your solution if the power is not a primary key but each power should be unique in the answer?

Solutions

Solution 1

# Write your MySQL query statement below
WITH
  T AS (
    SELECT
      power,
      CASE power
        WHEN 0 THEN IF(factor > 0, CONCAT('+', factor), factor)
        WHEN 1 THEN CONCAT(
          IF(factor > 0, CONCAT('+', factor), factor),
          'X'
        )
        ELSE CONCAT(
          IF(factor > 0, CONCAT('+', factor), factor),
          'X^',
          power
        )
      END AS it
    FROM Terms
  )
SELECT
  CONCAT(GROUP_CONCAT(it ORDER BY power DESC SEPARATOR ""), '=0') AS equation
FROM T;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文