1 string sub(string s1,string s2) 2 { 3 int flag = 0; 4 if(s1.length()<s2.length() || (s1.length()==s2.length() && s1 < s2)) 5 { 6 flag = 1; 7 string temp=s1; 8 s1=s2; 9 s2=temp; 10 } 11 12 13 int i,j; 14 for(i=s1.length()-1,j=s2.length()-1;i>=0;i--,j--) 15 { 16 s1[i]=char(s1[i]-(j>=0?s2[j]-'0':0)); //注意细节 17 if(s1[i]-'0'<0) 18 { 19 s1[i]=char(s1[i] + 10); 20 s1[i-1]--; 21 } 22 } 23 24 for(i = 0; i < s1.length(); i++) 25 { 26 if(s1[i] != '0') break; 27 } 28 if(i == s1.length()) i = s1.length()-1; 29 s1 = s1.substr(i); 30 31 if(flag) s1 = "-" + s1; 32 33 return s1; 34 }