C++程序:计算数组的比特数
给定一个整数数组,任务是使用函数计算给定数组的比特数。
数组的比特数是指:
- 初始化为0
- 当下一个元素大于前一个值时递增1
- 当下一个元素小于前一个值时递减1
示例
Input-: arr[] = { 1,4,3,5,2,9,10,11} Output-: Bitonicity of an array is : 3
解释:
- 将比特数计算变量(例如temp)初始化为0。
- 从数组的第一个元素1开始。现在比较arr[i]和arr[i-1],即比较4和1,这里4大于1,因此将temp递增1。类似地,比较4和3,由于3小于4,因此将temp的值递减。
- 打印temp的最终值,即3
下面程序中使用的方法如下:
- 遍历数组的所有元素,例如arr[n],其中n是数组的大小
- 如果arr[i] > arr[i-1],则比特数 = 比特数 + 1
- 如果arr[i] < arr[i-1],则比特数 = 比特数 – 1
- 如果arr[i] = arr[i-1],则比特数 = 比特数(不变)
算法
Start Step 1-> Declare function to calculate bitonicity of an array int cal_bitonicity(int arr[], int n) set int temp = 0 Loop For int i = 1 and i < n and i++ IF (arr[i] > arr[i - 1]) Increment temp++ End Else IF (arr[i] < arr[i - 1]) Decrement temp— End return temp step 2-> In main() declare int arr[] = { 1,4,3,5,2,9,10,11} set int n = sizeof(arr) / sizeof(arr[0]) Call cal_bitonicity(arr, n) Stop
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#include <iostream> using namespace std; // calculate bitonicity int cal_bitonicity(int arr[], int n) { int temp = 0; for (int i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) temp++; else if (arr[i] < arr[i - 1]) temp--; } return temp; } int main() { int arr[] = { 1,4,3,5,2,9,10,11}; int n = sizeof(arr) / sizeof(arr[0]); cout<<"Bitonicity of an array is : " <<cal_bitonicity(arr, n); return 0; }
输出
如果我们运行上述代码,它将生成以下输出:
Bitonicity of an array is : 3
广告