1006. Clumsy Factorial golang解

leetcode-cn.com/problems/cl…golang

一般,正整數 n 的階乘是全部小於或等於 n 的正整數的乘積。例如,factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1。bash

相反,咱們設計了一個笨階乘 clumsy:在整數的遞減序列中,咱們以一個固定順序的操做符序列來依次替換原有的乘法操做符:乘法(*),除法(/),加法(+)和減法(-)。app

例如,clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1。然而,這些運算仍然使用一般的算術運算順序:咱們在任何加、減步驟以前執行全部的乘法和除法步驟,而且按從左到右處理乘法和除法步驟。less

另外,咱們使用的除法是地板除法(floor division),因此 10 * 9 / 8 等於 11。這保證結果是一個整數。ide

實現上面定義的笨函數:給定一個整數 N,它返回 N 的笨階乘。函數

Normally, 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.ui

We instead make a clumsy factorial: using the integers in decreasing order, we swap out the multiply operations for a fixed rotation of operations: multiply (*), divide (/), add (+) and subtract (-) in this order.this

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.spa

Additionally, the division that we use is floor division such that 10 * 9 / 8 equals 11. This guarantees the result is an integer.設計

Implement the clumsy function as defined above: given an integer N, it returns the clumsy factorial of N.

解題思路: golang解 4個數字一組 每隔4循環調用f,f中除了小於等2 其餘調用公式 i/*(i-1)/(i-2) + (i-3)*toggle,使用toggle是由於第一組四個的最後一個數字(i-3)是加,後面的都變成減,好比 10*9/8+7 - (6*5/4-3) 由於後面一組加了括號加號要轉換成減號

func f(i int, toggle int) int {
	if i <= 2 {
		return i
	}
	return i*(i-1)/(i-2) + (i-3)*toggle
}

func clumsy(N int) int {
	var res int

	for i := N; i > 0; i -= 4 {
		if i == N {
			res = f(i, 1)
		} else {
			res -= f(i, -1)
		}
	}
	return res
}
複製代碼
相關文章
相關標籤/搜索