Leetcode-1523. 在区间范围内统计奇数数目

题目:

给你两个非负整数 lowhigh 。请你返回lowhigh之间(包括二者)奇数的数目。

示例 1:

复制代码
输入:low = 3, high = 7
输出:3
解释:3 到 7 之间奇数数字为 [3,5,7] 。

示例 2:

复制代码
输入:low = 8, high = 10
输出:1
解释:8 到 10 之间奇数数字为 [9] 。

提示:

  • 0 <= low <= high <= 10^9

第一种方法,直接判断奇数偶数,是奇数,计数器++;

java 复制代码
class Solution {
    public int countOdds(int low, int high) {

    int cnt = 0;

    if(low%2!=0){
        while(low<=high){
            cnt++;
            low+=2;
        }
    }
    if(low%2==0){
        low++;
        while(low<=high){
            cnt++;
            low+=2;
        }
    }
    
    return cnt;
    }
}

第二种,列出所有情况,high-low=0;low奇,high偶;high奇,low偶;low、high全奇全偶。

java 复制代码
class Solution {
    public int countOdds(int low, int high) {
        int cnt = 0;
        if(high-low==0){
            if(low%2==0)return cnt;
            return cnt+1;
        }
        if(low%2==0&&high%2==0){
            cnt+=(high-low)/2;
        }else if(low%2!=0&&high%2!=0){
            cnt+=((high-low)/2+1);
        }else{
            cnt+=(high-low+1)/2;
        }
        return cnt;
    }
}

第三种,一行代码秒杀!

java 复制代码
class Solution {
    public int countOdds(int low, int high) {
        return (high+1)/2 - low/2;
    }
}
相关推荐
Musennn12 分钟前
leetcode98.验证二叉搜索树:递归法中序遍历的递增性验证之道
java·数据结构·算法·leetcode
WLKQ12 分钟前
【力扣】关于链表索引
java·leetcode·链表
reduceanxiety43 分钟前
机试 | vector/array Minimum Glutton C++
数据结构·c++·算法
2301_794461571 小时前
力扣-最大连续一的个数
数据结构·算法·leetcode
xujinwei_gingko2 小时前
Spring boot基础
java·spring boot
啊阿狸不会拉杆3 小时前
《软件工程》第 14 章 - 持续集成
java·ci/cd·软件工程
清心歌3 小时前
二叉树遍历
数据结构·算法
武昌库里写JAVA3 小时前
Vue3编译器:静态提升原理
java·开发语言·spring boot·学习·课程设计
bing_1583 小时前
HttpServletRequest 对象包含了哪些信息?
java·spring·mvc