当前位置:网站首页>Li Kou daily question - day 29 -523 Count odd numbers in interval range
Li Kou daily question - day 29 -523 Count odd numbers in interval range
2022-06-28 03:37:00 【Chongyou research Sen】
2022.6.27 Did you brush the questions today
subject :
Here are two nonnegative integers low and high . Please return low and high Between ( Including both ) An odd number .
analysis :
Given an array , Find the number of odd numbers in this closed array , Note that you can take two numbers of array bounds .
Ideas : Let's go through this array , Returns the value when the element is odd ++, The final result .
analysis :
1. Violent solution
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. The mathematical formula
because 【0-x】 Number of odd numbers in the interval prex(x)=((x+1)÷2). therefore 【x,y】 In the interval, we can use prex(y)-prex(x) Get
class Solution {
public:
int pre(int x)
{
return (x + 1) /2;
}
int countOdds(int low, int high) {
return pre(high) - pre(low-1);
}
};边栏推荐
猜你喜欢

17 `bs object Node name h3 Parent ` parents get parent node ancestor node

Basic operation of stack (implemented in C language)

嵌入式软件开发中必备软件工具

可扩展数据库(下)

Summary of the use of composition API in the project

What are the technologies to be mastered in the test? Database design for software testing

Necessary software tools in embedded software development

Build your own website (17)

Change of monitoring documents and folders of "operation and maintenance department"

资源管理、高可用与自动化(下)
随机推荐
2022电工(初级)复训题库及在线模拟考试
Tardigrade:Trino 解决 ETL 场景的方案
What is the difference between slice and array in go question bank 12?
十年职场软件工程师感悟
Idea auto generate code
ARM Development Studio build编译报错
TypeScript 联合类型
How to automatically add author, time, etc. to eclipse
STM32外设SDIO和SD卡的配置
数据库乱码问题
2022安全员-C证考试题库模拟考试平台操作
空闲中断无法清除
数的每一位平方和
GAMES104 作业2-ColorGrading
Is it safe to buy stocks and open an account through the account opening link of the broker manager? Want to open an account for stock trading
嵌入式软件开发中必备软件工具
大咖说·计算讲谈社|什么是东数西算要解决的核心问题?
What is the core problem to be solved in the East and West?
Is Guotai Junan Securities reliable? Is it safe to open a securities account?
Use js programming questions [split] in Niuke