C++整数二分法

#include <iostream>
using namespace std;

int check(int mid) {
    return mid;
}

int bsearch_1(int l, int r) {
    while(l < r) {
        // 如果是r = mid的话则不需要加1
        int mid = (l + r) / 2;
        if(check(mid)) {
            r = mid;
        }else {
            l = mid + 1;
        }
    }
}

int bsearch_2(int l, int r) {
    while(l < r) {
        // 如果是l = mid的话则需要加1
        int mid = (l + r +  1) / 2;
        if(check(mid)) {
            l = mid;
        }else {
            r = mid - 1;
        }
    }
}
int main()
{





    return 0;
}

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要计算整数整数次方可以使用暴力求解或者使用二分法。下面是两种方法的示例代码: 方法一:暴力求解 ```c++ class Solution { public: double Power(double base, int exponent) { bool isFu = false; if(exponent < 0) { exponent *= (-1); isFu = true; } double res = 1; for(int i = 0; i < exponent; i++) { res *= base; } if(isFu) return 1/res; return res; } }; ``` 方法二:使用二分法 ```c++ class Solution { public: double Power(double base, int exponent) { bool isFu = false; // 判断是否为负数次方根 if(exponent < 0) { exponent *= (-1); isFu = true; } bool isStrange = false; // 判断是否为奇数 if(exponent % 2 != 0) { isStrange = true; exponent -= 1; } int count = 0; // 记录除2次数 while(exponent != 0 && exponent % 2 == 0) { count++; exponent /= 2; } double res = 1; // 记录结果 // 该情况exponent一开始为奇数,比如7,那么7-1 = 6,6/2 = 3,即不管如何都应该进行3次暴力乘法 for(int i = 0; i < exponent; i++) { res *= base; } // 通过记录的count次数,本身*本身即可。 for(int i = 0; i < count; i++) { res *= res; } // 如果为奇数,还应该进行一次乘法 if(isStrange) { res *= base; } // 如果为负数次方根 if(isFu) return 1/res; return res; } }; ``` 以上就是两种计算整数次方的方法,可以根据具体需求选择合适的方法进行计算。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [数值的整数次方(C++)](https://blog.csdn.net/qq135595696/article/details/125091372)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值