码迷,mamicode.com
首页 > 其他好文 > 详细

369. Plus One Linked List

时间:2019-01-01 12:27:05      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:new   etc   empty   number   problem   www   lint   answer   parse   

/**
* Lock by Leetcode
* 369. Plus One Linked List
* https://www.lintcode.com/problem/plus-one-linked-list/description
*
* Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.

 

Example
Given head = 1 -> 2 -> 3 -> null, return 1 -> 2 -> 4 -> null.
*/
/**
* @param head: the first Node
* @return: the answer after plus one
*/
const plusOne = function (head) {
  let str = "";
  while (head != null) {
    str += head.val;
    head = head.next;
  }
  let resultStr = addTwoString(str, "1");
  let arr = resultStr.split("");
  let newHead = new ListNode(parseInt(arr[0]));
  createList(newHead, 1, arr);
  return newHead;
};

 

var addTwoString = function (str1, str2) {
  let len1 = str1.length - 1, len2 = str2.length - 1;
  let carry = 0;
  let res = [];
  while (len1 >= 0 || len2 >= 0) {
  let a = len1 >= 0 ? str1.charAt(len1--) - ‘0‘ : 0;
  let b = len2 >= 0 ? str2.charAt(len2--) - ‘0‘ : 0;
  let temp = a + b + carry;
  if (temp >= 10) {
    carry = Math.floor(temp / 10);//10位
    temp = Math.floor(temp % 10);//个位
  } else
    carry = 0;
  res.unshift(temp);
  }
  if (carry)
  res.unshift(1);

  return res.join("");

};

 

var createList = function (head, index, arr) {
  if (index >= arr.length)
    return;
  let node = new ListNode(parseInt(arr[index]));
  head.next = node;
  createList(node, index + 1, arr.concat());
};

369. Plus One Linked List

标签:new   etc   empty   number   problem   www   lint   answer   parse   

原文地址:https://www.cnblogs.com/johnnyzhao/p/10204418.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!