leetCode
[Easy] 1523. Count Odd Numbers in an Interval Range
개발자 자두
2022. 5. 26. 11:42
문제
Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).
low부터 high까지 홀수가 몇 개인지 반환하는 문제이다.
예시
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
풀이 과정
이 문제도 쉽게 풀 수 있었다.
- 홀수의 개수를 셀 count 변수를 초기화한다.
- low부터 high까지 for문을 돈다.
- 만약 i / 2의 나머지가 1일 때(홀수일 때), count 증가시킨다.
- for문을 다 돌고난 후 count를 반환한다.
풀이 코드
/**
* @param {number} low
* @param {number} high
* @return {number}
*/
var countOdds = function(low, high) {
let count = 0;
for(let i = low ; i <= high ; i++){
if(i % 2 === 1) count++;
}
return count;
};