415. Add Strings


Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

思路:按照位相加,多余的位数只需要加进位就可以了,如果是最后进位为1,千万不要忘了。

代码:

1.是从末尾开始相加,还要注意进位。

2.返回的是string类型,用arrays的话在leetcode提交不成功。

3.数组的下表是一门技巧。

public class Solution {
    public String addStrings(String num1, String num2) {
             int min=Math.min(num1.length(), num2.length());//短字符串
		int max=Math.max(num1.length(), num2.length());//长字符串
		int [] num=new int[max];//相加之后的数组
		int carry=0;	//表示进位

		for(int i=0;i<min;i++)
		{
			int n1=num1.charAt(num1.length()-i-1)-'0';
			int n2=num2.charAt(num2.length()-i-1)-'0';
			num[max-i-1]=n1+n2+carry;//从0-min都可以相加,注意数组下表
			if(num[max-i-1]>=10)//进位
			{
				num[max-i-1]-=10;
				carry=1;
			}
			else
			{
				carry=0;
			}
		}
		if(num1.length()>num2.length())//长字符串是num1时

		{
			for(int i=0;i<max-min;i++){
				int n1=num1.charAt(max-min-i-1)-'0';//按位进行运算,字符减去'0'得到的就是整数,可以直接进行相加
				num[max-min-i-1]=n1+carry;
				if(num[max-min-i-1]>=10)
				{
					num[max-min-i-1]-=10;
					carry=1;
				}
				else
				{
					carry=0;
				}
			}
		}
		else
		{
			for(int i=0;i<max-min;i++){
			    int n2=num2.charAt(max-min-i-1)-'0';
				num[max-min-i-1]=n2+carry;
				if(num[max-min-i-1]>=10)
				{
					num[max-min-i-1]-=10;
					carry=1;
				}
				else
				{
					carry=0;
				}
			}
		}
	    StringBuffer sb=new StringBuffer();//用stringBuffer来转换
	    if(carry!=0)
			sb.append(carry);//如果最后还是有进位,要加上
		for(int i=0;i<num.length;i++){
			sb.append(num[i]);
		}
		return sb.toString();//转换为string类型
    }
}

  

posted @ 2017-06-05 11:27  牛虻爱吃饭  阅读(138)  评论(0编辑  收藏  举报