這次我除法改用另一種方法,因為覺得上次沒效率
ex 861 / 21 = 41
861
21
-----------
45
21
-----------
23
21
-----------
21
21
----------
0
跟上次一樣 n2是除數,L2是n2的長度
else{
// 直式除法
string temp="", left=n2;
vector<int> ans;
for (int i=0; i<L2; i++){
temp += n1[i];
}
int Index = L2;
for (int i=0; i<=L1-L2; i++){
int Plus=0, Check=0;
while (1){
if (temp.length() < n2.length())
break;
n2.insert(0,string(temp.length() - n2.length(),'0'));
for (int i=0; i<temp.length(); i++){
if (temp[i] < n2[i]){
Check = 1;
break;
}
else if (temp[i] > n2[i]){
Check = 0;
break;
}
}
if (Check == 1)
break;
// 快速減法
vector<int> Num_1={}, Num_2={}, Ans={};
for (int i=0; i<temp.length(); i++){
Num_1.push_back(int(temp[i]) - 48);
Num_2.push_back(int(n2[i]) - 48);
}
int borrow = 0;
for (int i=Num_1.size()-1; i>=0; i--){
int Insert = Num_1[i] - Num_2[i] - borrow;
if (Insert < 0){
Insert += 10;
borrow = 1;
}
else
borrow = 0;
Ans.push_back(Insert);
}
reverse(Ans.begin(),Ans.end());
while (Ans[0] == 0)
Ans.erase(Ans.begin());
temp = "";
for (int i=0; i<Ans.size(); i++){
string N_S;
stringstream s1;
s1 << Ans[i];
s1 >> N_S;
temp += N_S;
}
Plus += 1;
if (temp == "")
temp += "0";
}
temp += n1[Index];
Index += 1;
n2 = left;
ans.push_back(Plus);
}
for (int i=0; i<ans.size(); i++) cout << ans[i] << '\n';
}
這個除法會回傳奇怪的值,幫我看一下,謝謝!
while (Ans[0] == 0)
Ans.erase(Ans.begin());
當Ans是0的時候,所有元素都會被移除,可是迴圈還是會繼續跑,所以會出現undefined behavior
感謝!! 已AC~~