public static String twoNumberAdd(String num1,String num2){
return String.valueOf(ListToString(addTwoNumbers(StringToList(num1),StringToList(num2))));
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode sum = new ListNode();
ListNode target = sum;
int carry = 0;
int i = 0;
int j = 0;
while (l1 != null || l2 != null) {
i = l1 == null ? 0 : l1.val;
j = l2 == null ? 0 : l2.val;
int a = i + j;
sum.next = new ListNode((a + carry) % 10);
sum = sum.next;
if (a + carry >= 10) {
carry = 1;
} else {
carry = 0;
}
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
if (carry == 1) sum.next = new ListNode(1);
return target.next;
}
public static ListNode StringToList(String string){
ListNode sum = new ListNode();
ListNode target = sum;
for (int i = string.length() - 1; i >= 0; i--) {
sum.next = new ListNode(Integer.parseInt(String.valueOf(string.charAt(i))));
sum = sum.next;
}
return target.next;
}
public static StringBuffer ListToString(ListNode listNode){
if (listNode == null) return new StringBuffer();
StringBuffer stringBuffer = ListToString(listNode.next);
stringBuffer.append(listNode.val);
return stringBuffer;
}
两个无长度限制相加算法【Java】
最新推荐文章于 2024-11-16 17:49:09 发布