从写这个code,学到了char[]和char *的区别,最大的不同就是如果char *指向的是string literal, 内容不可更改,所以这里传入参数应该是由char[]定义的。
- //assume that no negative integers are involved.
- //reverse a c string
- void reverse(char *c, int start, int end){
- while(start < end){
- char tmp = c[start];
- c[start++] = c[end];
- c[end--] = tmp;
- }
- }
- char* MultiplyString(char *a,char *b){
- int m = strlen(a), n = strlen(b);
- //one extra position for carry, another one extra position for '\0'
- char *c = new char[m+n+1];
- memset(c, '0', m+n);
- reverse(a,0,m-1);
- reverse(b,0,n-1);
- int carry;
- //for each position in b, do the multiplication of b[i]*a,update corresponding positions in result c.
- for(int i = 0; i < n; i++){
- carry = 0;
- for(int j = 0; j < m; j++){
- int prod = (b[i] - '0')*(a[j] - '0') + carry + (c[i+j] - '0');
- carry = prod/10;
- c[i+j] = prod%10 + '0';
- }
- }
- //deal with the highest position's carry
- if(carry != 0) {
- c[m+n-1] = '0' + carry;
- reverse(c,0,m+n-1);
- }
- else {
- c[m+n-1] = '\0';
- reverse(c,0,m+n-2);
- }
- return c;
- }
swap(a,b):
a = a^b
b = b^a
a = a^b
No comments:
Post a Comment