当问题非常简单的时候,解题重点就从优化时间复杂度变成了优化代码简洁性。
输入长短不一就都放在 while loop 里,在读取字符时把短的做 padding.
While loop 里三个 'OR' 的条件保证了三种不同情况下都会继续读取,而其他两个自动 pad 0.
犯错一: 漏了最后carry不为0时要append
犯错二: 先append 该位值再update carry
public class Solution {
public String addBinary(String a, String b) {
int lena = a.length()-1; int lenb = b.length()-1;int carry=0;
StringBuilder sb = new StringBuilder();
while(lena>=0 || lenb>=0){
int vala; int valb;
vala = lena>=0?a.charAt(lena--)-'0':0;
valb = lenb>=0?b.charAt(lenb--)-'0':0;
sb.insert(0, (vala+valb+carry)%2);
carry = (vala+valb+carry)/2;
}
if(carry!=0) sb.insert(0, carry);
return sb.toString();
}
}
犯错一: 漏了最后carry不为0时要append
犯错二: padding时 两个指针不为空是或的关系
犯错三: 判断指针p不为空时 才能p.next
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0); ListNode l3 = head; int carry = 0;
while(l1!=null || l2!=null){
int val1 = l1!=null?l1.val:0;
int val2 = l2!=null?l2.val:0;
l3.next = new ListNode((val1+val2+carry)%10);
carry =(val1+val2+carry)/10;
if(l1!=null) l1=l1.next;
if(l2!=null) l2=l2.next;
l3=l3.next;
}
if(carry!=0) l3.next = new ListNode(carry);
return head.next;
}
}
m位数乘n位数一定是小于等于m+n的数
a位数字乘b位数字, 结果保存在sum[a+b]
返回字符串不能以0开头, 除非返回0
public class Solution {
public String multiply(String num1, String num2) {
int[] sum = new int[num1.length()+num2.length()];
StringBuilder sb1 = new StringBuilder(num1).reverse();
StringBuilder sb2 = new StringBuilder(num2).reverse();
for(int i=0;i<sb1.length();i++)
for(int j=0;j<sb2.length();j++){
sum[i+j]+=(sb1.charAt(i)-'0')*(sb2.charAt(j)-'0');
}
StringBuilder sb = new StringBuilder();
int carry = 0;
for(int i=0;i<sum.length;i++){
sb.append((sum[i]+carry)%10);
carry = (sum[i]+carry)/10;
}
for(int i=sb.length()-1;i>=0&&sb.length()>1;i--){
if(sb.charAt(i)=='0') sb.deleteCharAt(i);
else break;
}
return sb.reverse().toString();
}
}
Divide String