[LeetCode]Clumsy Factorial

2024. 4. 6. 20:50·SW개발/코딩테스트

https://leetcode.com/problems/clumsy-factorial/

 

LeetCode - The World's Leading Online Programming Learning Platform

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

 

문제 분석

Factorial의 연산을 * / + - 연산자를 순서대로 rotation하면서 계산한 결과를 구하는 문제입니다.

 

처음 시도한 답안

class Solution:
    def clumsy(self, n: int) -> int:
        if n == 1:
            n = 1
        elif n == 2:
            n = 2
        elif n == 3:
            n = 6
        elif n == 4:
            n = 7
        elif n % 4 == 0:
            n = n + 1
        elif n % 4 == 1 or n % 4 == 2:
            n = n + 2
        elif n % 4 == 3:
            n = n - 1
    
        return n

접근 방법

  1. n을 키우면서 연산을 하다보면 5번째부터 규칙을 발견할 수 있습니다.
  2. 1~4까지는 1, 2, 6, 7의 연산 결과를 갖게됩니다.
  3. 그보다 큰 숫자는 나머지에 따라서 n보다 1이 크거나 2가 크거나 1이 작은 수가 되게 됩니다.

이 문제의 경우 1~4까지는 고정된 결과, 5 이후로는 특정 패턴이 반복되는 문제입니다. 이 패턴에 따라 적절하게 분기처리하여 풀이할 수 있습니다.

이러한 방법 말고도 스택을 사용해서도 풀이할 수 있는 문제로 알고있습니다.

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Course Schedule  (0) 2024.04.08
[LeetCode]Number of Islands  (0) 2024.04.07
[LeetCode]Complex Number Mutiplication  (0) 2024.04.05
[LeetCode]Diagonal Traverse  (0) 2024.04.04
[LeetCode]Game of Life  (0) 2024.04.03
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Course Schedule
  • [LeetCode]Number of Islands
  • [LeetCode]Complex Number Mutiplication
  • [LeetCode]Diagonal Traverse
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (307)
      • SW개발 (303)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (1)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    음식
    오픈소스
    g
    배공파용
    라이프 스타일
    Contributor
    어플리케이션
    컨트리뷰터
    배달
    django
    플레이스토어
    트리 #AVL #알고리즘 #자료구조
    배달비 공유
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Clumsy Factorial
상단으로

티스토리툴바