昨天我学了二分代码,就想着发上来给大家看看。
这就是代码:
#include<algorithm>
#include<iostream>
using namespace std;
//本代码用来求从left到right中找n需要多少(left<right)
int l = 0, r = 45, cnt = 0, n;
void BinarySearch() {
int mid;
while (l <= r) {
mid = (l + r) / 2;
if (n == mid) {
cnt++;
return;
}
else if (mid > n) {
r = mid - 1;
cnt++;
}
else if (mid < n) {
l = mid + 1;
cnt++;
}
}
}
int main() {
cin >> n;
BinarySearch();
cout << cnt;
//Write your Code!
return 0;
}
//By cowedge