当前位置:网站首页>力扣每日一题-第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);
}
};边栏推荐
猜你喜欢

mysql获取当前时间是一年的第多少天

在excel文件上设置下拉选项

More, faster, better and cheaper. Here comes the fastdeploy beta of the low threshold AI deployment tool!

CI & CD 不可不知!

失联修复:让“躲猫猫”无处可藏

项目实战!手把手教你 Jmeter 性能测试

Build your own website (17)

数据库系列之MySQL和TiDB中慢日志分析

用于 C# 的 SQL 基本语法总结

Import an excel file, solve the problem of skipping blank cells without reading and moving the subscript forward, and return_ BLANK_ AS_ Null red
随机推荐
物体上下漂浮工具
电子地图坐标系统研究整理
Apache——阿帕奇简介
Hot! Yolov6's fast and accurate target detection framework is open source (with source code download)
荣耀v8 真机调试时不显示 Logcat 日志的解决办法
Introduction to kubernetes resource object and common commands
Documentation issues
云应用、服务的“5层”架构
可扩展数据库(下)
R1 Quick Open Pressure Vessel Operation Special Operation Certificate Examination Library and Answers in 2022
Redis cluster setup [simple]
栈的基本操作(C语言实现)
17 `bs object Node name h3 Parent ` parents get parent node ancestor node
TypeScript 联合类型
WARN:&nbsp; SQL&nbsp; Error:&nbsp;…
Go 数据类型篇(四)之浮点型与复数类型
十年职场软件工程师感悟
How to write concise code? (upper)
数据库系列之MySQL中的分页查询优化
SSH框架的搭建(下)