返回介绍

solution / 1000-1099 / 1006.Clumsy Factorial / README_EN

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

1006. Clumsy Factorial

中文文档

Description

The factorial of a positive integer n is the product of all positive integers less than or equal to n.

  • For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.

We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*', divide '/', add '+', and subtract '-' in this order.

  • For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1.

However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.

Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11.

Given an integer n, return _the clumsy factorial of _n.

 

Example 1:

Input: n = 4
Output: 7
Explanation: 7 = 4 * 3 / 2 + 1

Example 2:

Input: n = 10
Output: 12
Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1

 

Constraints:

  • 1 <= n <= 104

Solutions

Solution 1

class Solution:
  def clumsy(self, N: int) -> int:
    op = 0
    s = [N]
    for i in range(N - 1, 0, -1):
      if op == 0:
        s.append(s.pop() * i)
      elif op == 1:
        s.append(int(s.pop() / i))
      elif op == 2:
        s.append(i)
      else:
        s.append(-i)
      op = (op + 1) % 4
    return sum(s)
class Solution {
  public int clumsy(int N) {
    Deque<Integer> s = new ArrayDeque<>();
    s.offerLast(N);
    int op = 0;
    for (int i = N - 1; i > 0; --i) {
      if (op == 0) {
        s.offerLast(s.pollLast() * i);
      } else if (op == 1) {
        s.offerLast(s.pollLast() / i);
      } else if (op == 2) {
        s.offerLast(i);
      } else {
        s.offerLast(-i);
      }
      op = (op + 1) % 4;
    }
    int res = 0;
    while (!s.isEmpty()) {
      res += s.pollLast();
    }
    return res;
  }
}

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

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

发布评论

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