{ "cells": [ { "cell_type": "markdown", "source": [ "Normally, the factorial of a positive integer `n` is the product of all\n", "positive integers less than or equal to `n`. For example, `factorial(10) = 10\n", "* 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`.\n", "\n", "We instead make a _clumsy factorial:_ using the integers in decreasing order,\n", "we swap out the multiply operations for a fixed rotation of operations:\n", "multiply (*), divide (/), add (+) and subtract (-) in this order.\n", "\n", "For example, `clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1`. However,\n", "these operations are still applied using the usual order of operations of\n", "arithmetic: we do all multiplication and division steps before any addition or\n", "subtraction steps, and multiplication and division steps are processed left to\n", "right.\n", "\n", "Additionally, the division that we use is _floor division_ such that `10 * 9\n", "/ 8` equals `11`. This guarantees the result is an integer.\n", "\n", "`Implement the clumsy` function as defined above: given an integer `N`, it\n", "returns the clumsy factorial of `N`.\n", "\n", "\n", "\n", "**Example 1:**\n", "\n", "\n", "\n", " Input: 4\n", " Output: 7\n", " Explanation: 7 = 4 * 3 / 2 + 1\n", "\n", "\n", "**Example 2:**\n", "\n", "\n", "\n", " Input: 10\n", " Output: 12\n", " Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1\n", "\n", "\n", "\n", "\n", "**Note:**\n", "\n", " 1. `1 <= N <= 10000`\n", " 2. `-2^31 <= answer <= 2^31 - 1` (The answer is guaranteed to fit within a 32-bit integer.)" ], "metadata": {} }, { "outputs": [ { "output_type": "execute_result", "data": { "text/plain": "clumsy (generic function with 1 method)" }, "metadata": {}, "execution_count": 1 } ], "cell_type": "code", "source": [ "# @lc code=start\n", "using LeetCode\n", "\n", "function clumsy(N::Int)\n", " if N <= 4\n", " return [1, 2, 6, 7][N]\n", " end\n", " mod = 1 + (N & 3)\n", " return N + [1, 2, 2, -1][mod]\n", "end\n", "# @lc code=end" ], "metadata": {}, "execution_count": 1 }, { "cell_type": "markdown", "source": [ "---\n", "\n", "*This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*" ], "metadata": {} } ], "nbformat_minor": 3, "metadata": { "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.10.1" }, "kernelspec": { "name": "julia-1.10", "display_name": "Julia 1.10.1", "language": "julia" } }, "nbformat": 4 }