2022.6.27今天你刷题了吗
题目:
给你两个非负整数 low
和 high
。请你返回 low
和 high
之间(包括二者)奇数的数目。
分析:
给定一个数组,找到这个闭合数组里面奇数的个数,注意可以取数组边界的两个数。
思路:我们遍历这个数组,当元素为奇数时返回值++,最终得到结果。
解析:
1.暴力求解
class Solution {
public:
int countOdds(int low, int high) {
int res = 0;
for (int i = low; i <= high; i++)
{
if (i % 2 != 0)
{
res++;
}
}
return res;
}
};
2.数学公式
由于【0-x】区间内奇数个数prex(x)=((x+1)÷2).所以【x,y】区间内我们可以利用prex(y)-prex(x)求得
class Solution {
public:
int pre(int x)
{
return (x + 1) /2;
}
int countOdds(int low, int high) {
return pre(high) - pre(low-1);
}
};