兩個36進製的大整數以字串的形式給出,求出兩個大整數的和,並以字串方式輸出。(頭條面試題)
比如:12346 + gsftyhs = gsgw1ly
publicclass
format36
public
static
string sum(string num1, string num2)
num2 =sb.tostring();
}if(num1.length() num1 =sb.tostring();
}int add = 0;//
進製 stringbuilder sb = new
stringbuilder();
for (int i = num1.length() - 1; i >= 0; i--)
if(add != 0)
sb.insert(0, add);
return
sb.tostring();
}}
映象:給定兩個非空鍊錶來代表兩個非負整數。數字最高位位於鍊錶開始位置。它們的每個節點只儲存單個數字。將這兩數相加會返回乙個新的鍊錶。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
高階:如果輸入鍊錶不能修改該如何處理?換句話說,你不能對列表中的節點進行翻轉。
示例:
輸入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)leetcode:輸出: 7 -> 8 -> 0 -> 7
思路:用棧實現:
publiclistnode addtwonumbers(listnode l1, listnode l2)
while (l2 != null
)
int add = 0;//
進製int value1 = 0;
int value2 = 0;
listnode ago = null
; listnode node = null
;
while (!stack1.isempty() || !stack2.isempty())
else
if (!stack2.isempty())
else
int sum = value1 + value2 +add;
node = new listnode(sum % 10);
add = sum / 10;
node.next =ago;
ago =node;
}if (add > 0)
return
node;
}
反轉單鏈表實現:
publiclistnode addtwonumbers2(listnode l1, listnode l2)
else
if (l2 != null
) else
int sum = value1 + value2 +add;
node = new listnode(sum % 10);
add = sum / 10;
node.next =ago;
ago =node;
}if (add > 0)
//把鍊錶改回來
l1 =reverselist(l1);
l2 =reverselist(l2);
return
node;
}public
listnode reverselist(listnode head)
return
pre;
}
演算法筆記 大整數相加
大整數相加,這裡用string輸入,轉為int型別陣列存數,陣列低位存整數的低位 個位存在index 0的地方 include include const int maxlen 10000 struct bign void str2bign char str,int n,bign bign retu...
大整數相加
include include include include 思路如下 將兩個字串分別由低位到高位放置到int陣列中 然後每位對齊相加,大於10,本位取餘,高位進1 char bigintadd const char numstr1,const char numstr2 for i len1 i ...
大整數相加
cpp view plain copy code class cpp include include include include 思路如下 將兩個字串分別由低位到高位放置到int陣列中 然後每位對齊相加,大於10,本位取餘,高位進1 char bigintadd const char numst...