LeetCode - 1523. Count Odd Numbers in an Interval Range(Math)

YAMAMAMO·2022년 3월 7일
0

LeetCode

목록 보기
38/100

문제

음이 아닌 두 개의 정수가 낮음과 높음입니다. 낮음과 높음(포함) 사이의 홀수 개수를 반환합니다.

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].

풀이

자바입니다.

  • int count = high-low+1 은 high와 low 사이의 숫자 개수입니다.
  • high 와 low 가 홀 수일 경우 +1을 해준다.
    ex) 3,4,5,6,7,8,9,10,11 - > 3,5,7,9,11 -> 5 개
    count = 9 -> 9/2 -> 4(int형이므로 소수점은 버린다.)+1 -> 5 개
class Solution {
    public int countOdds(int low, int high) {
        if(low == 0 && high == 0) return 0;
        if(low == high && low%2 == 1) return 1;
        int count = high - low + 1;
    
        if(low%2==1&&high%2==1) return count/2+1;
        else return count/2;
        
    }
}
profile
안드로이드 개발자

0개의 댓글