1、 對任意輸入的正整數N,編寫C程式求N!的尾部連續0的個數,並指出計算複雜度。如:18!=6402373705728000,尾部連續0的個數是3。(不用考慮數值超出電腦整數界限的問題)
思路:就是求N中5的個數
解答:
int num;//結尾0的個數
num=0;
while(N)
{
num+=N/5;
N/=5;
}
2、請實現兩棵樹是否相等的比較,相等返回1,否則返回其他值,並說明演算法複雜度。
資料結構為:
typedef struct_TreeNode{
char c;
TreeNode *leftchild;
TreeNode *rightchild;
}TreeNode;
函數介面為:int CompTree(TreeNode* tree1,TreeNode* tree2);
註:A、B兩棵樹相等若且唯若Root->c==RootB-->c,而且A和B的左右子樹相等或者左右互換相等。
解答:
int CompTree(TreeNode* tree1,TreeNode* tree2){
if(!tree1&&!tree2) return 1;
else if((tree1->c==tree2->c)&&(CompTree(tree1->leftchild,tree2->leftchild)&&(CompTree(tree1->rightchild,tree2->rightchild))) return 1;
else return 0;
}
3、已知一個字串由GBK漢字和ansi編碼的數字字母混合組成,編寫c語言函數實現從中去掉所有ansi編碼的字母和數字(包括大小寫),要求在原字串上返回結果。
函數介面為:int filter_ansi(char* gbk_string)
註:漢字的GBK編碼範圍是0x8140-0xFEFE
我這裡沒有區別編碼的問題,漢字就是佔兩個位元組,並且最高位為1
#include <stdio.h> #include <stdlib.h>
int isnum(int ch) { if(ch>='0' && ch<='9') return 1; else return 0; }
int iszimu(int ch) { if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z')) return 1; else return 0; }
int filter_ansi(char* gbk_string) { int i = 0; int filter = 0; char* tmp = gbk_string; while(*tmp) { if(isnum(*tmp) || iszimu(*tmp)) { filter++; tmp++; } else if(*tmp&0x80) { gbk_string[i] = *tmp; i++; tmp++; gbk_string[i] = *tmp; i++; tmp++; } else tmp++; } gbk_string[i] = '\0'; return filter; } int main(int argc, char *argv[]) { char gbk_string[] = "a1我b2是c3A誰"; printf("original str is %s\n", gbk_string); printf("filter %d chars\n", filter_ansi(gbk_string)); printf("after the str is:%s\n", gbk_string); system("PAUSE"); return 0; }
|
這是個編碼問題,你可以查看下
編碼名稱 第一位元組 第二位元組
gb2312 0xB0-0xF7 0xA0-0xFE
GBK 0x81-0xFE 0x40-0xFE
BIG5 0x81-0xFE 0x40-0x7E or 0xA1--xFE
我這裡簡單起見,就直接用第一個位元組的高位為1了....
如果沒記錯的話,全形輸入的漢字,符號都是高位為1。如這裡的(,。)
*tmp&0x80 是為了確定*tmp最高位是否為1