https://oj.leetcode.com/problems/add-binary/
这个题目不是他别难,但要把string转成int[]却费了一番功夫。当然不转也可以。我的程序一如既往的笨拙。
当中有个while()循环。有一些专门对两个链表或数组操作的题目。
需要注意的是有的时候是或(||)符号,有的时候是并且符号(&&)
主要是看这两个链表要不要一定出现。比如如果是比较的话,确一个就没办法比较,所以用&&
如果是求和,缺一个也可以。所以用||。
public class Solution {
public String addBinary(String a, String b) {
if(a==null)return b;
if(b==null)return a;
if(a==null&&b==null)return null;
char[]aa=a.toCharArray();
char[]bb=b.toCharArray();
int len1=aa.length;
int len2=bb.length;
int[]aaa=new int[len1];
int[]bbb=new int[len2];
for(int i=0;i<len1;i++){
aaa[i]=aa[i]-'0';
}
for(int j=0;j<len2;j++){
bbb[j]=bb[j]-'0';
}
StringBuffer sb=new StringBuffer();
int i=len1-1;
int j=len2-1;
int carry=0;
int sum=0;
while(i>=0||j>=0){
if(i>=0){
sum+=aaa[i];
i--;
}
if(j>=0){
sum+=bbb[j];
j--;
}
sum+=carry;
sb.append(sum%2);
carry=sum/2;
sum=0;
}
if(carry==1){
sb.append(1);
}
return sb.reverse().toString();
}
}
比如这道题
https://oj.leetcode.com/submissions/detail/15398174/
让你合并两个已经排好序的链表。
注意while循环里的符号是&&。
实际上写的又麻烦了,可以继续改进。
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)return l2;
if(l2==null)return l1;
if(l1==null&&l2==null)return null;
ListNode ret=new ListNode(-1);
ListNode p1=l1;
ListNode p2=l2;
ListNode pp=ret;
while(p1!=null&&p2!=null){
if(p1.val<p2.val){
pp.next=p1;
p1=p1.next;
pp=pp.next;
}else{
pp.next=p2;
p2=p2.next;
pp=pp.next;
}
}
if(p1!=null)
<span style="white-space:pre"> </span> pp.next=p1;
<span style="white-space:pre"> </span> <span style="white-space:pre"> </span>if(p2!=null)
<span style="white-space:pre"> </span> pp.next=p2;
<span style="white-space:pre"> </span>
return ret.next;
}
}