华为机考题1
1.找出一個數組中滿足2^N的元素
#include <iostream> using namespace std; int find(int a[],int len); void main() {int a[]={1,2,3,5,7,8,16};int len=sizeof(a)/sizeof(int);cout<<find(a,len)<<endl;}int find(int a[],int len){int i;int count=0;for(i=0;i<len;i++){if(0==(a[i]&(a[i]-1))) //與運算之后為0,說明是2的冪count++;}return count;} View Code2.報數:共n個人 從1編號,設從第s個人報號,報到m出隊
最容易理解的一種方法:
#include<iostream> using namespace std;void Joseph(int n, int m, int s);int main() {Joseph(9,3,1);return 0; }void Joseph(int n, int m, int s) {int i,j,w;int s1 = s;int a[100] = {0};for(i = 0; i < n; i++){a[i] = i + 1;} //先編號for(i = n; i>= 2; i--){s1 = (s1+m-1)%i; //每報一次出去的人的編號,而后總人數-1,i就是人數,每循環一次就-1if(s1 == 0){s1 = i; //一旦數到最后一個元素,s1的值就變成i=元素總數,因為這是求余運算 }w = a[s1-1];//出去的元素值, //出隊人的值for(j = s1; j < i; j++){a[j-1] = a[j]; //只剩i-1個元素,依次往前序號-1; }a[i-1] = w; //出去的元素存在最后一個位置,依次往前排列 }for(int k = n-1; k >= 0; k--)cout<<a[k]<<" ";cout<<endl;} View Code3.統計一個數二進制表達中0的個數(首位1之前0不計)
#include <iostream> using namespace std;int fun(int num); int main() {int num;cout<<"Please enter a integer:\n";cin>>num;cout<<fun(num)<<endl;return 0; }int fun(int num) {int count = 0; while (num){if ((num & 1)==0){ //按位與1進行與,結果為0,表示此位為0,然后原數右移count++;}num = num >> 1;}return count; } View Code4.鏡像反轉二進制表達式,并輸出十進制值
#include<iostream> using namespace std; int func(int a); main() {int n;cout<<"enter:";cin>>n;cout<<func(n)<<endl; }int func(int a) {int val=0;int temp;int i;int n=0;int b[100];while(a!=0){temp=(a&1);b[n++]=temp;a=(a>>1);} //先把二進制數翻轉,存于數組中,for(i=0;i<n;i++)val=val*2+b[i];//val=val+(2^(n-1-i))*b[i]; //每一位的值相加得到return val;} View Code5.判斷一個字符串中()是否配對
#include<iostream> using namespace std; bool match(char a[],int length); int main(){ char b[100];int len;bool m;cout<<"enter:"<<endl;gets(b);len=strlen(b);m=match(b,len);if(m) cout<<"match"<<endl;else cout<<"nonmatch"<<endl;return 0;}bool match(char a[],int length){ char *p=a;int count1=0;int count2=0;while(*p!='\0')//當沒有到尾部時 { if(*p=='(') count1++;if(*p==')') count2++;if(count2>count1)return false;//使用指針和一個計數器;。 p++;}if(count1==count2) return true;else return false; } View Code6.鏈表倒序
Node *Reverse(Node *head) {Node *p1,*p2,*p3;if(head==NULL||head->next==NULL)return head;p1=head;p2=p1->next;while(p2){p3=p2->next;p2->next=p1;p1=p2;p2=p3;}head->next=NULL;head=p1;return head; }7.查找子字符串個數
#include <iostream> #include <string> using namespace std;int fun(char *str, char *substr);int main() {char str[100];char substr[10];cout<<"輸入字符串:\n";gets(str);cout<<"輸入字串:\n";gets(substr);cout<<fun(str, substr)<<endl;return 0; }int fun(char *str, char *substr) {int count = 0;while (*str){char *p = str;char *q = substr;while (*q){if (*p == *q){p++;q++;}else{break;}}if (*q == 0) //到達子字符串的末尾,開始從新的為止開始比較 {str = str + strlen(substr);count++;}else{str++; //直到兩個串的開始字母是相同的為止 }}return count; }?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
總結
- 上一篇: SQL 索引知识
- 下一篇: Design Patterns in J