LeetCode Solution, Medium, 2. Add Two Numbers

Search for a command to run...

No comments yet. Be the first to comment.
現在應該開始有很多人想要踏入軟體工程的領域,但在進入這個領域之前,覺得先了解一些名詞,可以在入門時更有方向也更知道要用什麼關鍵字去找尋有用的資訊。這篇文章就是想要幫助想要入門的人理解一些軟體工程裡的專有名詞。 作業系統 這一區塊主要解釋跟作業系統層面相關的名詞 英文中文解釋 Operation system 簡稱 OS | 作業系統 | 就是電腦的作業系統,是三大作業系統分別是:Linux、Windows、macOS | | Linux | | 自由和開放原始碼的 UNI...
現在開始因為 ChatGPT 的出現,各種 AI 助手的功能都跑出來了。想想自己用了許久的環境設定也應該要來重新審視和建立新的開發環境了,僅此紀錄我個人的環境配置步驟和設定。 環境前置步驟 還原 MacBook Pro 至全新環境 macOS(全部資料刪除) 設定好初始設定後,登入 Apple ID 進入 App Store 確定 macOS 版本和預設 APP 都更新到最新 macOS 版本 到系統設定調整所有設定至個人習慣的設定 三指拖移 觸控板手勢開啟 防火牆開啟 輸入法設定...
從 ChatGPT 問世到現在,有許許多多的文章和討論出來。先從最早的 Google 要完蛋了,到後來的工作要被取代了,工程師失業了。 我就比較沒有想要馬上出來評論一下,我喜歡讓子彈飛一會兒。跟討論一下我自己比較在意的討論點。 Google 為什麼慢了? 結論:因為他需要更小心 很多人說 Google 怎麼被微軟搶先了一步。剛開始 Bing 說要加上 AI 的時候大家都在說 Google 怎麼慢了。我就馬上跑去看 OpenAI 的網站,靠北呀啊就 Azure 贊助的。那當然在正式上線 ChatG...
囤積癖
607. Sales Person 題目敘述 SQL Schema > Create table If Not Exists SalesPerson (sales_id int, name varchar(255), salary int, commission_rate int, hire_date date) Create table If Not Exists Company (com_id int, name varchar(255), city varchar(255)...
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 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Constraints:
[1, 100].0 <= Node.val <= 9給兩個資料結構為 Linked List 的參數 l1 和 l2,每個節點都只會有一個位數的值。要將兩個 list 相加。
解題方式是最開始的個位數都是在最前面,所以其實很方便的就是從頭去開始遍歷來計算。當超過 10 就記住商數到參數 carry 帶到下個節點。
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
head := &ListNode{Val: 0}
n1, n2, carry, current := 0, 0, 0, head
for l1 != nil || l2 != nil || carry != 0 {
if l1 == nil {
n1 = 0
} else {
n1 = l1.Val
l1 = l1.Next
}
if l2 == nil {
n2 = 0
} else {
n2 = l2.Val
l2 = l2.Next
}
current.Next = &ListNode{Val: (n1 + n2 + carry) % 10}
current = current.Next
carry = (n1 + n2 + carry) / 10
}
return head.Next
}
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function (l1, l2) {
const head = new ListNode(0);
let p = l1,
q = l2,
curr = head,
carry = 0;
while (p || q || carry) {
const x = p ? p.val : 0;
const y = q ? q.val : 0;
const sum = x + y + carry;
carry = Math.floor(sum / 10);
curr.next = new ListNode(sum % 10);
curr = curr.next;
p = p ? p.next : null;
q = q ? q.next : null;
}
return head.next;
};
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun addTwoNumbers(l1: ListNode, l2: ListNode): ListNode {
val result = ListNode(0)
var current = result
var l1Current: ListNode? = l1
var l2Current: ListNode? = l2
var carry = 0
while (l1Current != null || l2Current != null || carry > 0) {
val sum = (l1Current?.`val` ?: 0) + (l2Current?.`val` ?: 0) + carry
carry = sum / 10
val node = ListNode(sum % 10)
current?.next = node
current = node
l1Current = l1Current?.next
l2Current = l2Current?.next
}
return result.next
}
}
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* }
*/
class Solution
{
/**
* @param ListNode $l1
* @param ListNode $l2
* @return ListNode
*/
function addTwoNumbers($l1, $l2)
{
$dummyHead = new ListNode(0);
$p = $l1;
$q = $l2;
$curr = $dummyHead;
$carry = 0;
while ($p || $q || $carry) {
$x = $p ? $p->val : 0;
$y = $q ? $q->val : 0;
$sum = $x + $y + $carry;
$carry = intval($sum / 10);
$curr->next = new ListNode($sum % 10);
$curr = $curr->next;
$p = $p ? $p->next : null;
$q = $q ? $q->next : null;
}
return $dummyHead->next;
}
}
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy_head = ListNode(0)
p = l1
q = l2
curr = dummy_head
carry = 0
while p or q or carry:
x = p.val if p else 0
y = q.val if q else 0
carry, remain = divmod(x + y + carry, 10)
curr.next = ListNode(remain)
curr = curr.next
p = p.next if p else None
q = q.next if q else None
return dummy_head.next
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut p = l1;
let mut q = l2;
let mut dummyHead = Some(Box::new(ListNode::new(0)));
let mut curr = dummyHead.as_mut();
let mut carry = 0;
while p.is_some() || q.is_some() || carry > 0{
let mut sum = carry;
if let Some(node) = p {
sum += node.val;
p = node.next;
}
if let Some(node) = q {
sum += node.val;
q = node.next;
}
if let Some(node) = curr {
node.next = Some(Box::new(ListNode::new(sum % 10)));
curr = node.next.as_mut();
}
carry = if sum >= 10 { 1 } else { 0 };
}
return dummyHead.unwrap().next;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let dummyHead = ListNode( 0 )
var p = l1, q = l2, curr = dummyHead, carry = 0, r = 0, x = 0, y = 0, sum = 0
while p != nil || q != nil {
x = p?.val ?? 0
y = q?.val ?? 0
sum = x + y + carry
(carry,r) = sum.quotientAndRemainder(dividingBy: 10)
curr.next = ListNode( r )
curr = curr.next!
p = p?.next
q = q?.next
}
if ( carry > 0 ) {
curr.next = ListNode(1)
}
return dummyHead.next
}
}