본문 바로가기
Algorithm/LeetCode

[LeetCode] 1523 | Count Odd Numbers in an Interval Range

by 밤초록 2023. 4. 3.
1523 | Count Odd Numbers in an Interval Range
https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/

 

Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).

 

 

Example 1:

 

Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].

 

Example 2:

 

Input: low = 8, high = 10
Output: 1
Explanation: The odd numbers between 8 and 10 are [9].

 

Constraints:

  • 0 <= low <= high <= 10^9

 

 

작성 코드

 

sum 이용 (실패)

 

class Solution:
    def countOdds(self, low: int, high: int) -> int:
        nums = [num for num in range(low, high + 1) if num % 2 == 1]
        return len(nums)

 

  • 시간 초과!

 

 

패턴 파악 (통과)

 

class Solution:
    def countOdds(self, low: int, high: int) -> int:
        if low % 2 == 0 and high % 2 == 0:
            return (high - low) // 2
        if low % 2 == 1 and high % 2 == 1:
            return 2 + (high - low - 1) // 2
        else:
            return (high - low) // 2 + 1

 

  • 시작과 종료가 각각 홀수, 짝수일 때를 나누어 계산

 

 

이상 코드

 

class Solution:
    def countOdds(self, low, high):
        return (high + 1) // 2 - low // 2

 

  • 깔끔 !!
  • 패턴 파악을 잘 해야 되는 문제인데 수학 !
  • 짝수는 -> 1 ~ n 까지라면, n - (n + 1) // 2 --> n 에서 홀수의 개수를 뺌
반응형

댓글