2816. Double a Number Represented as a Linked List
T: O(n)
S: O(n)
```java
/**
* 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; }
* }
*/
import java.math.*;
class Solution {
public ListNode doubleIt(ListNode head) {
StringBuilder sb = new StringBuilder();
ListNode dummy = head;
while (dummy != null) {
sb.append(dummy.val);
dummy = dummy.next;
}
//System.out.println(sb.toString());
// BigDecimal out = new BigDecimal(sb.toString());
// BigDecimal mOut = out.multiply(new BigDecimal("2"));
// String o = String.valueOf(mOut);
int carry = 0;
char[] c = sb.toString().toCharArray();
int num = (c[c.length-1] - '0')*2;
carry = num/10;
num = num%10;
ListNode pre = new ListNode(num);
if (c.length == 1 && carry == 0) {
return pre;
}
ListNode cur = null;
for (int i = c.length-2; i >= 0; i--) {
num = (c[i] - '0')*2 + carry;
carry = num/10;
num = num%10;
cur = new ListNode(num);
cur.next = pre;
pre = cur;
}
if (carry != 0) {
cur = new ListNode(carry);
cur.next = pre;
}
return cur;
}
}
```
Smarter - use recursion
T :O(n)
S: O(1)
```java
/**
* 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 doubleIt(ListNode head) {
int t = multiply(head);
ListNode cur = head;
if (t != 0) {
cur = new ListNode(t);
cur.next = head;
}
return cur;
}
private int multiply(ListNode node) {
if (node == null) {
return 0;
}
int t = node.val*2 + multiply(node.next);
node.val = t%10;
return t/10; // carry
}
}
```
Last updated