레벨업 일지

[Java] leetcode 1523. Count Odd Numbers in an Interval Range 본문

알고리즘/leetcode

[Java] leetcode 1523. Count Odd Numbers in an Interval Range

24시간이모자란 2023. 2. 13. 23:04

문제

https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/description/

 

Count Odd Numbers in an Interval Range - LeetCode

Can you solve this real interview question? 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 Explanati

leetcode.com

풀이

쉬어가는 문제.

로직은 다음과 같다. 

  • [ 0 .. low ] 0이상 low 이하 의 홀수 개수 를 구한다. 
  • [ 0 .. high ] 0 이상 high 이하의 홀수 개수를 구한다. 
  • 두개의 차를 해주고, low 가 홀수이면 1을 더해준다.

 

코드

class Solution {
    public int countOdds(int low, int high) {
        return (high+1) /2  - (low+1) /2 +low%2;
    }
}
Comments