41.题目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
class Solution { public: int Sum_Solution(int n) { char a[n][n+1]; return sizeof(a)>>1; } };
42.题目描述
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
class Solution { public: int Add(int num1, int num2) { if(num1 == 0) return num2; if(num2 == 0){ return num1; } return Add(num1^num2,(num1&num2)<<1); } };
43.题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
class Solution { public: int StrToInt(string str) { if(str.length()==0){ return 0; } int symbol = 0; int val = 0; if(str[0]=='+'){ symbol=1; }else if(str[0]=='-'){ symbol=-1; }else if(str[0]-'0'>=0 && str[0]-'0'<10){ val = str[0]-'0'; symbol=1; } for(int i=1;i<str.length();i++){ if(str[i]-'0'>10 || str[i]-'0'<0){ return 0; } val = val*10 + str[i]-'0'; } return val*symbol; } };
44.题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。
class Solution { public: // Parameters: // numbers: an array of integers // length: the length of array numbers // duplication: (Output) the duplicated number in the array number // Return value: true if the input is valid, and there are some duplications in the array number // otherwise false bool duplicate(int numbers[], int length, int* duplication) { map<int,int>a; for(int i=0;i<length;i++){ a[numbers[i]]++; } for(auto it=a.begin();it!=a.end();it++){ if(it->second>1){ *duplication = it->first; return true; } } return false; } };
45.题目描述
给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。
思路:
利用两个辅助数组,
第一个数组L依次保存A数组从
0
-length-
1
的乘积,
第二个数组h依次保存从length-
1
到
0
的乘积,
然后每一个要求的B[i]=L[i-
1
]*H[i+
1
].
//B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1] //从左到右算 B[i]=A[0]*A[1]*...*A[i-1] //从右到左算B[i]*=A[i+1]*...*A[n-1] class Solution { public: vector<int> multiply(const vector<int>& A) { int n=A.size(); vector<int> b(n); int ret=1; for(int i=0;i<n;ret*=A[i++]){ b[i]=ret; } ret=1; for(int i=n-1;i>=0;ret*=A[i--]){ b[i]*=ret; } return b; } };
46.题目描述
请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
class Solution { public: bool match(char* str, char* pattern) { if (*str == '