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].
난이도: easy
이 문제는 홀수인 숫자를 찾는 것으로
무조건 O(1)로 풀어야 된다라고 생각이 든게 그냥 들었다
반복문으로 풀면 나눠서 count++ 해주면 되는데 이러면 분명 효율이 맨끝으로 갔을 것 같다
var countOdds = function(low, high) {
let count = 0;
if (low % 2 === 1 || high % 2 === 1) count++
count = count + Math.floor((high - low) / 2);
return count;
};
문제에서 생각해줘야 할 부분은
1. low: 홀수, high: 홀수
2. low, high 둘 중 하나 홀수
3. low: 짝수, high: 짝수
이렇게만 생각해주면 된다
Math.floor를 해줘서 둘 중 하나가 홀수인 경우를 해결해준다고 생각하면 된다
풀이할 때 공책에 하나씩 적어가면서 규칙이 어떤지 찾아봤다
암산으로는 도저히 안풀려서 ㅋㅋㅋ
반응형
'Algorithm' 카테고리의 다른 글
[Leetcode] 1491. Average Salary Excluding the Minimum and Maximum Salary (0) | 2022.03.17 |
---|---|
[Leetcode] 1137. N-th Tribonacci Number (0) | 2022.03.17 |
[Leetcode] 509. Fibonacci Number (0) | 2022.03.17 |
[Leetcode] 2176.Count Equal and Divisible Pairs in an Array (0) | 2022.03.12 |
[Leetcode] 21. Merge Two Sorted Lists (0) | 2022.03.12 |