๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/Leetcode

[Leetcode] Clumsy Factorial (#1006)

 

 

๋ฌธ์ œ 

 

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

 

 

ํ•ด์„ค ์ฝ”๋“œ 
class Solution:
    def clumsy(self, n):
        res = ""
        j = -1
        for i in range(n,0,-1):
            res += str(i)
            j += 1
            if j < n - 1:
                if j % 4 == 0:
                    res += "*"
                if j % 4 == 1:
                    res += "//"
                if j % 4 == 2:
                    res += "+"
                if j % 4 == 3:
                    res += "-"
        return eval(res)
๋ถ„์„ > ์–ด๋ ค์šด ๋ฌธ์ œ๋Š” ์•„๋‹ˆ์—ˆ๋Š”๋ฐ ํ˜ผ์ž ๋„ˆ๋ฌด ๊ผฌ์•„์„œ ์ƒ๊ฐํ–ˆ๋˜ ๊ฒƒ ๊ฐ™๋‹ค. n๊นŒ์ง€์˜ ์ˆซ์ž๋ฅผ ๊ฑฐ๊พธ๋กœ ํ•˜๋‚˜์”ฉ ์ถ”๊ฐ€ํ•˜๋ฉด์„œ ์ธ๋ฑ์Šค๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” j์˜ ํฌ๊ธฐ์— ๋”ฐ๋ผ ๋ถ€ํ˜ธ๋ฅผ ์ถ”๊ฐ€ํ•˜๊ณ  ๋งˆ์ง€๋ง‰์— eval ๋‚ด์žฅํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด ์ˆ˜์‹์œผ๋กœ ๊ณ„์‚ฐํ•˜๋ฉด ๋˜์—ˆ๋‹ค. eval ์ด๋ผ๋Š” ํŽธ๋ฆฌํ•œ ๋‚ด์žฅํ•จ์ˆ˜๋ฅผ ์ด์ œ์•ผ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค๋‹ˆ ... 

 

 

 

 

Clumsy Factorial - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

'Algorithm > Leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leetcode] Validate Stack Sequences (#946)  (0) 2022.04.21
[Leetcode] Create Target Array in the Given Order (#1389)  (0) 2022.04.21
[Leetcode] Print Words Vertically (#1324)  (0) 2022.04.20
[Leetcode] Reshape the Matrix (#566)  (0) 2022.04.20
[Leetcode] Complex Number Multiplication (#537)  (0) 2022.04.20