【leetCode】2_にすう加算

1227 ワード

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode la = new ListNode(0), lt = la;
        int tc = 0, c = 0, s = 0;
        while(l1 != null || l2 != null || c != 0){
            if (l1 != null && l2 != null) {
                s = (l1.val + l2.val + c) % 10;
                c = (l1.val + l2.val + c) / 10;
                l1 = l1.next;
                l2 = l2.next;
            }
            else if (l1 != null || l2 != null){
                if(l1 != null){
                    s = (l1.val + c) % 10;
                    c = (l1.val + c) / 10;
                    l1 = l1.next;
                }
                else if (l2 != null){
                    s = (l2.val + c) % 10;
                    c = (l2.val + c) / 10;
                    l2 = l2.next;
                }
            }
            else{
                s = c;
                c = 0;
            }
            lt.next = new ListNode(s);
            lt = lt.next;

        }
        la = la.next;
        return la;
    }
}