Notice
Recent Posts
Recent Comments
Today
Total
01-11 03:54
Link
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Partially Committed

[LEETCODE] 1523. Count Odd Numbers in an Interval Range ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm || ๋ฌธ์ œํ’€์ด/PS

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

WonderJay 2022. 10. 9. 15:28
728x90
๋ฐ˜์‘ํ˜•
SMALL

https://leetcode.com/

TITLE : 1523. Count Odd Numbers in an Interval Range

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

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

upper boundary ๊ฐ€ 10^9 ์ด๋ฏ€๋กœ, brute-force ๋กœ ์ˆœํšŒํ•˜๋ฉด์„œ ํ™€์ˆ˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๋ฉด TLE ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

์•„๋ž˜ ์„ธ ๊ฐ€์ง€ ์ผ€์ด์Šค๋กœ ๋ถ€ํ„ฐ O(1) ํ’€์ด๋ฅผ ์ƒ๊ฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

[1, 5] ์˜ ๊ฒฝ์šฐ ๋‘ ๊ฒฝ๊ณ„๊ฐ€ ๋ชจ๋‘ ํ™€์ˆ˜์ด๋‹ค.

๋‘ ์ˆ˜ ์‚ฌ์ด์— ์กด์žฌํ•˜๋Š” ์ˆซ์ž๋“ค์˜ ๊ฐœ์ˆ˜(inclusive)๋Š” 5-1+1 = 5 ๊ฐœ์ด๊ณ  ์ด๋“ค ์ค‘ ํ™€์ˆ˜์˜ ๊ฐœ์ˆ˜๋Š” 5/2+1 = 3๊ฐœ์ด๋‹ค.

 

[2,5] ์˜ ๊ฒฝ์šฐ ๋‘ ๊ฒฝ๊ณ„ ์ค‘ ํ•˜๋‚˜๋Š” ์ง์ˆ˜, ํ•˜๋‚˜๋Š” ํ™€์ˆ˜์ด๋‹ค.

๋‘ ์ˆ˜ ์‚ฌ์ด์— ์กด์žฌํ•˜๋Š” ์ˆซ์ž๋“ค์˜ ๊ฐœ์ˆ˜๋Š” 5-2+1 = 4 ๊ฐœ์ด๊ณ  ์ด๋“ค ์ค‘ ํ™€์ˆ˜์˜ ๊ฐœ์ˆ˜๋Š” 4/2 = 2 ๊ฐœ์ด๋‹ค.

 

[2,6] ์˜ ๊ฒฝ์šฐ ๋‘ ๊ฒฝ๊ณ„ ๋ชจ๋‘ ์ง์ˆ˜์ด๋‹ค.

๋‘ ์ˆ˜ ์‚ฌ์ด์— ์กด์žฌํ•˜๋Š” ์ˆซ์ž๋“ค์˜ ๊ฐœ์ˆ˜๋Š” 6-2+1 = 5๊ฐœ์ด๊ณ  ์ด๋“ค ์ค‘ ํ™€์ˆ˜์˜ ๊ฐœ์ˆ˜๋Š” 5/2 = 2 ๊ฐœ์ด๋‹ค.

 

[C++]

class Solution {
public:
    int countOdds(int low, int high) {
        int cnt = high - low + 1;
        if(high %2 == 1 && low %2 == 1){
            // both odd
            return cnt/2+1;
        }
        else{
            return cnt/2;
        }
    }
};

 

728x90
๋ฐ˜์‘ํ˜•
LIST
Comments