saurus2
Saurus2
saurus2
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발
      • AJAX
    • ML Ops
    • Profile
    • 음식점
    • 배낭여행
    • 컴퓨터공학
      • 알고리즘 공부
      • C++
      • Sever 스터디
      • Java spring
      • 알고리즘 _ 문제해결
      • 딥러닝
      • Java 정리
      • Python
      • LeetCode 1000
      • Machine Learning Study
      • Sign language Detection Pro..
      • LeetCode Solutions
    • 비콘
    • 데일리 리포트
    • 유학일기
      • 영어 공부
      • Daily
    • AI Master Degree
      • Data Mining
      • AI and Data engineering
      • Math Foundations for Decisi..
      • Natural Language Processing

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 취업준비
  • 문제해결능력
  • c++
  • LeetCode
  • 개발자 취업준비
  • 파이썬
  • 백준
  • 딕셔너리
  • two pointer
  • Python
  • 알고리즘
  • BFS
  • 개발자
  • 릿코드
  • 알고리즘문제해결
  • 딥러닝
  • 취준
  • 온라인저지
  • DFS
  • 리트코드

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
saurus2

Saurus2

컴퓨터공학/LeetCode 1000

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

2023. 2. 14. 06:23

1523. Count Odd Numbers in an Interval Range

Easy

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

문제 풀이

  • 숫자 두개가 주어진다.
  • 두개 숫자들을 포함하여 숫자들 사이에 있는 모든 홀수의 갯수를 구하여라.
  • 문제 풀이 제한을 보면 숫자의 최대값이 10^9이기 때문에 O(1) 시간복잡도로 풀어야한다.
  • 두개의 숫자 사이에 존재하는 숫자들은 짝수 반, 홀수 반이라고 생각할 수 있다.
  • 예를들어 1 부터 5일 경우 홀수는 1, 3, 5 짝수는 2, 4가 있다.
  • 여기서 두가지 경우로 나눌 수 있다.
  • 1 2 3 4 5: low와 high둘 중의 하나라도 홀수가 있는 경우에 홀수가 짝수보다 1개가 많다.
  • 2 3 4 5 6: low와 high둘다 짝수라면 홀수는 두개 짝수는 세개가 된다. 
  • 이를 활용하여 문제를 풀 수 있는데, high 에서 low를 빼고 2로 나누면 각각 숫자의 개수가 나온다.
  • 둘다 짝수일때는 홀수가 반이 있다고 가정할 수 있으며, 그게 아니라면 1을 더해줘야한다.

소스 코드

class Solution:
    def countOdds(self, low: int, high: int) -> int:
        ans = (high - low) // 2
        if low % 2 == 0 and high % 2 == 0:
            return ans
        else:
            return ans + 1
저작자표시 (새창열림)

'컴퓨터공학 > LeetCode 1000' 카테고리의 다른 글

[LeetCode] 280. Wiggle Sort  (0) 2023.02.14
[LeetCode] 2477. Minimum Fuel Cost to Report to the Capital  (0) 2023.02.12
[LeetCode] 567. Permutation in String  (0) 2023.02.10
[LeetCode] 6. Zigzag Conversion  (1) 2023.02.04
[LeetCode] 1056. Confusing Number  (0) 2023.01.02
    '컴퓨터공학/LeetCode 1000' 카테고리의 다른 글
    • [LeetCode] 280. Wiggle Sort
    • [LeetCode] 2477. Minimum Fuel Cost to Report to the Capital
    • [LeetCode] 567. Permutation in String
    • [LeetCode] 6. Zigzag Conversion
    saurus2
    saurus2
    Simple is Best

    티스토리툴바