leetcode
Java
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 contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself.
有兩個非空的linked list代表的整數,其中每個節點包含一個數字。數字存儲按照在原來整數中相反的順序。寫出一個函數將兩個整數相加,用linked list形式回傳兩者的合。
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
carry
變數(0->沒有進位,1->有進位)curr
中指向result
下一個節點在做同樣的計算,l1
l2
則判斷是否下一個節點是否NULL也指向下一個節點
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);//設定新的空鏈結儲存結果
ListNode curr = result;
int carry = 0;//進位
while(l1 != null || l2 != null) {
int x = (l1!=null) ? l1.val: 0;
int y = (l2!=null) ? l2.val: 0;
int sum = x + y + carry;
if(sum >= 10) carry = 1;
else carry = 0;
curr.next = new ListNode(sum%10);
curr = curr.next;
if(l1 != null) l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
//carry = 1
if(carry == 1) curr.next = new ListNode(1);
return result.next;//回傳鏈結的第一個節點
}
}
Description Given a string s, return the longest palindromic substring in s. 給定一個String,並找出最長的回文子字串(palindromic substring),如有多個相同長度的最長子字串可只回傳一個 Example Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer.
Aug 18, 2021Description The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
Aug 18, 2021Description Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). 將整數反轉,遇到超過32-bit的數就回傳0 Example Input: x = 123 Output: 321
Aug 15, 2021Description Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 給一字符串數組, 將錯位詞(指相同字符不同排列的字符串) 分組 Example Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Aug 15, 2021or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up