leetcode66,67

66Plus One

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

数组代表一个数字 在这个数组的基础上加1再把这个数字以数组存储的方式返回

 public int[] plusOne(int[] digits) {
          List<Integer> res = new ArrayList<>();
             int sum=1;//存储上一位求和后的进位数字 开始为1
		   int digit=0;//存储新数对应位数字
		   for(int index=digits.length-1;index>=0;index--)
		   {
			   //新数字每一位都等于原数字的对应位+sum 然后取个位数
               sum=digits[index]+sum;
			   digit=sum%10;//取个位
			   res.add(digit);
			   sum=sum/10;
			
		   }
		 if(sum!=0)//如果遍历完数组还要进一位
		 {
			 res.add(sum);		
		 }
		
	    //生产返回数组
		 int[] a=new int[res.size()];  
		for(int i=res.size()-1;i>=0;i--)
		{
			a[res.size()-i-1]=res.get(i);
			
		}
		 return a;
	    
	   
    }

leetcode高票

 int n=digits.length-1;
		   	for(int i=n;i>=0;i--)
		   	{
		   		if(digits[i]<9)
		   		{
		   			digits[i]++;
		   			return digits;
		   		}
		   		digits[i]=0;
		   	}
		   	int[] newarry = new int[n+2];
		   	newarry[0]=1;
		   	return newarry;
    }

67Add Binary


Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"


 public String addBinary(String a, String b) {
         StringBuffer sb = new StringBuffer();
		      int i = a.length()-1;
		      int j = b.length()-1;
		      int carry=0;//存储进位的数字
		      while(i>=0||j>=0)
		      {
		    	 int sum =carry;
		    	  if(i>=0) sum+=a.charAt(i--)-'0';
		    	  if(j>=0) sum+=b.charAt(j--)-'0';
                 /**
                  *   sum的结果由上次运算的进位数字加a串加b串三部分组成
                  *   结果   sum        要存入的数字  sum%2     进位  sum/2
                  *   0      			 0         		0
                  *   1      			 1        		0
                  *   2     			 0        		1
                  *   3    	 			 1         		1
                 
                  */
                  
		    	  sb.append(sum%2);
		    	  carry=sum/2;
		      }
		    if(carry!=0)sb.append(carry);
            return sb.reverse().toString();
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值