【笔试刷题训练】day_11

我想说

每天坚持一点点,坚持带来大改变
今天是刷题的第_11天,加油!


编程题

1.最小公共祖先

👉 题目链接

递归方式

image-20221023113301523

class LCA {
public:
    int getLCA(int a, int b) {
        // write code here
        if(a==b)    return a;
        //如果b的父亲还大于等于a,a不动,b动
        if(a<=b/2)
        {
            return getLCA(a,b/2);
        }
        else if(b<=a/2)
        {
            return getLCA(a/2,b);
        }
        else
        {
            return getLCA(a/2,b/2);
        }
        
    }
};

循环方式

image-20221023113308623

class LCA {
  public:
    int getLCA(int a, int b) {
        while (a != b) {
            //如果a大,a去找a的父亲
            if(a > b)
                a /= 2;
            //否则b去找b的父亲
            else
                b /= 2;
        }
        //相等时跳出循环 返回其中一个即可
        return a;
    }
};

2. 最大连续bit数

👉 题目链接
在这里插入图片描述

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int n;
    cin >> n;
    int count = 0;	//记录当前count
    int Max = 0;	//记录最大个数
    for(int i = 0;i<32;++i)
    {
        if(((n>>i)&1) == 1)
        {
            ++count;
            Max = max(Max,count);//更新最大1的个数
        }
        else    //遇到非0 重新计数
        {
            count = 0;
        }
    }
    cout << Max << endl;
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2021狮子歌歌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值