好吧到今天開始我就完成了leetcode第二個(gè)主題字柠,每天一道編程題必須要堅(jiān)持下去绑榴,這次我做的題大多是讓兩個(gè)東西相加孽鸡,這個(gè)東西可以是兩個(gè)整型字符串蹂午、二進(jìn)制字符串、整型鏈表等等彬碱。
我個(gè)人覺得這道題的靈感主要是來自《數(shù)字邏輯》里面的全加器豆胸,這個(gè)全加器大約是這個(gè)樣子的
A和B是兩個(gè)本位數(shù)Cin是來自低位的進(jìn)位,S是面向高位的進(jìn)位巷疼,基本上依靠這個(gè)就能把這類題的最主要的大體循環(huán)結(jié)構(gòu)搞出來了:
示例代碼
//假設(shè)傳入的參數(shù)是兩個(gè)整型字符串num1和num2
StringBuilder stringBuilder = new StringBuilder();
for (int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; ) {
int sum = carry;
if (i >= 0) sum += num1.charAt(i--) - '0';
if (j >= 0) sum += num2.charAt(j--) - '0';
stringBuilder.append(sum % 10);
carry = sum / 10;
}
來道例題:
- Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
然后我的解題方法是:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode corrent = new ListNode(-20);
ListNode result = corrent;
for (ListNode list1 = l1, list2 = l2; list1 != null || list2 != null || carry > 0; ) {
int sum = carry;
if (list1 != null) {
sum += list1.val;
list1 = list1.next;
}
if (list2 != null) {
sum += list2.val;
list2 = list2.next;
}
corrent.next = new ListNode(sum % 10);
corrent = corrent.next;
carry = sum / 10;
}
return result.next;
}
emmm最后的運(yùn)行情況:
類似的題還有這些: