文章目录
问题
1217: 统计立方数
时间限制: 1 Sec 内存限制: 128 MB
提交: 1939 解决: 932
题目描述
有一堆正整数,统计其中有多少立方数。
输入
输入数据有一些正整数,其每个数都小于2^32。若该数为0,则应结束统计。
输出
输出所统计的立方数个数
样例输入 Copy
1 3 5 7 9 11 15 17 19 21 23 25 27 0
样例输出 Copy
2
代码
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
#define ElementType int
int BinarySearch(const ElementType A[], int N, ElementType X);
int findNumBinarySearch(int *arr, int len, int num);
int cubicNumArr[1300];
const unsigned int maxInt = -1 + (1 << 31);
int main() {
long num = 0, i = 0;
// 生成立方数 数组
while (num <= maxInt) {
cubicNumArr[i] = num;
i++;
num = pow(i, 3);
}
int len = i;
int cnt = 0;
while(cin >> num, num != 0) {
if (BinarySearch(cubicNumArr, len, num))
{
cnt++;
}
}
cout << cnt << endl;
return 0;
}
int findNumBinarySearch(int * arr, int length, int num) { // 二分查找
int begin, end, mid;
int len = length;
begin = 0, end = len - 1;
while(begin <= end) {
mid = (begin + end) / 2;
if (arr[mid] > num) {
end = mid - 1;
}
else if (arr[mid] < num) {
begin = mid + 1;
}
else {
return 1;
}
}
return 0;
}
int BinarySearch(const ElementType A[], int N, ElementType X) {
int Low, Mid, High;
Low = 0; High = N - 1;
while (Low <= High) {
Mid = (Low + High) / 2;
if (A[Mid] < X) Low = Mid + 1;
else if (A[Mid] > X) High = Mid - 1;
else return 1; /* Found */
}
return 0; /* NotFound is defineed as 0 */
}
小结
数组二分查找(函数实现)
int BinarySearch(const ElementType A[], int N, ElementType X) {
int Low, Mid, High;
Low = 0; High = N - 1;
while (Low <= High) {
Mid = (Low + High) / 2;
if (A[Mid] < X) Low = Mid + 1;
else if (A[Mid] > X) High = Mid - 1;
else return 1; /* Found */
}
return 0; /* NotFound is defineed as 0 */
}
加油吧!!!
刷起来!!!