每天一题LeetCode[第四天]
Add Two Numbers
Description:
You are given
two non-
empty linked lists representing
two non-negative integers. The digits are stored
in reverse order
and each of their nodes contain
a single digit. Add
the two numbers
and return it as a linked list.
You may assume
the two numbers
do not contain
any leading
zero, except
the number 0 itself.
Input: (
2 ->
4 ->
3) + (
5 ->
6 ->
4)
Output:
7 ->
0 ->
8
Subscribe
to see which companies asked this question.
解题思路:
这题比较简单,思路也是十分容易得出来。 小细节:就是如果用List数据结构,建议用两次for循环来写,逻辑更加清晰,虽然效率相对低了点,但是可读性大大提高。ps:如果有更好的解法,欢迎留言~
Java代码:
public class Solution {
private static final String TAG= Solution.class.getSimpleName();
public static void main(String [] args){
List<Integer> numb1=
new ArrayList<>();
List<Integer> numb2=
new ArrayList<>();
numb1.add(
2);
numb1.add(
4);
numb1.add(
3);
numb2.add(
5);
numb2.add(
6);
numb2.add(
4);
List<Integer> result=addTwoNumbs(numb1,numb2);
System.
out.println(result.toString());
}
public static List<Integer>
addTwoNumbs(List<Integer> numb1, List<Integer> numb2){
if(
null==numb1 ||
null==numb2){
return Collections.emptyList();
}
List<Integer> lNumbs,sNumbs;
if(numb1.size()<numb2.size()){
lNumbs=numb2;
sNumbs=numb1;
}
else{
lNumbs=numb1;
sNumbs=numb2;
}
for(
int i=
0; i<sNumbs.size();i++){
lNumbs.
set(i,lNumbs.
get(i)+sNumbs.
get(i));
}
boolean bit=
false;
for(
int i=
0;i<lNumbs.size();i++){
int num=lNumbs.
get(i);
if(bit){
if(i==lNumbs.size()-
1 && num==
9){
lNumbs.add(
1);
}
else{
num++;
}
}
if(num>=
10){
bit=
true;
}
else{
bit=
false;
}
lNumbs.
set(i,num%
10);
}
return lNumbs ;
}
}
提高代码质量就是:每天积累精美的思路,优质的细节的过程。
转载请注明原文地址: https://ju.6miu.com/read-114212.html