当前位置:网站首页>力扣每日一题-第29天-523.在区间范围统计奇数数目
力扣每日一题-第29天-523.在区间范围统计奇数数目
2022-06-28 02:43:00 【重邮研究森】
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);
}
};
边栏推荐
- Is Guotai Junan Securities reliable? Is it safe to open a securities account?
- Import an excel file, solve the problem of skipping blank cells without reading and moving the subscript forward, and return_ BLANK_ AS_ Null red
- 数据库系列之MySQL和TiDB中慢日志分析
- Basic operation of stack (implemented in C language)
- collections. Use of defaultdict()
- 暴雨去哪儿?天气预报不准谁的锅?
- 可扩展存储系统(上)
- 大咖说·计算讲谈社|什么是东数西算要解决的核心问题?
- Flow based depth generation model
- Documentation issues
猜你喜欢
【小程序】使用font-awesome字体图标的解决文案(图文)
Tardigrade: Trino's solution to ETL scenarios
View the SQL execution plan according to explain and optimize the SQL
CI & CD 不可不知!
暴雨去哪儿?天气预报不准谁的锅?
Redis cluster setup [simple]
如何获取GC(垃圾回收器)的STW(暂停)时间?
Importer un fichier Excel, résoudre le problème de sauter les cellules vides et de ne pas lire, et avancer l'indice, et retourner Blank As NULL Red
导入Excel文件,解决跳过空白单元格不读取,并且下标前移的问题,以及RETURN_BLANK_AS_NULL报红
s32ds跳转到DefaultISR
随机推荐
电子地图坐标系统研究整理
Go speed
项目实战!手把手教你 Jmeter 性能测试
音视频技术开发周刊 | 251
大咖说·计算讲谈社|什么是东数西算要解决的核心问题?
What are the good practices of cloud cost optimization?
WARN:&nbsp;SQL&nbsp;Error:&nbsp;…
Dataloader parameter collate_ Use of FN
Notepad++--常用的插件
十年职场软件工程师感悟
【小程序】使用font-awesome字体图标的解决文案(图文)
资源管理、高可用与自动化(中)
Yes, it's about water
可扩展存储系统(上)
GAMES104 作业2-ColorGrading
WARN:&nbsp; SQL&nbsp; Error:&nbsp;…
ARM Development Studio build编译报错
Object类,以及__new__,__init__,__setattr__,__dict__
物体上下漂浮工具
database