标签:set 技术分享 enc mat ret style img main .com
法则
减法的算法也是从低位开始减,先要判断减数和被减数那一个位数长,减数位数长是正常减;
被减数位数长,则被减数减减数,最后还要加上负号;两个位数长度相等时,最好比较那一个数字大,否则负号会处理的很繁琐;
处理每一项时,如果前一位相减有错位,就先减上一位的错位,无则不减,再去判断是否能够减开被减数,
如果减不开,就要借位后再去减,同时错位为1,否则置错位为0.
#include<iostream> #include<stdio.h> #include<math.h> #include<string.h> using namespace std; int main() { char a[1005]; char b[1005]; int aa[1005]; int bb[1005]; int c[1005]; while(~scanf("%s%s",a,b)) { memset(aa,0,sizeof(aa)); memset(bb,0,sizeof(bb)); int lena = strlen(a); int lenb = strlen(b); int sign = 0; //用于判断正负数 if( (lenb > lena ) || (lena == lenb && strcmp(b,a) > 0)) { sign = 1; swap(a,b); } for(int i = lena - 1; i >= 0; i--) { aa[lena - i -1] = a[i] - ‘0‘; } for(int i = lenb - 1; i >= 0; i--) { bb[lenb - i -1] = b[i] - ‘0‘; } int lenc = lena > lenb ? lena : lenb; int jiewei = 0 ; for(int i = 0 ; i < lenc ; i++) { if(aa[i] - bb[i] +jiewei < 0) { c[i] = aa[i] - bb[i] + jiewei +10; jiewei = -1; } else { c[i] = aa[i] - bb[i] +jiewei; jiewei = 0; } } while(c[lenc-1] == 0 && lenc > 1) { lenc--; } if(sign == 1) printf("-"); for(int i = 0; i < lenc; i++) { printf("%d",c[i]); } puts(""); } return 0; }
标签:set 技术分享 enc mat ret style img main .com
原文地址:http://www.cnblogs.com/hhkobeww/p/7657679.html