国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Leetcode030--二進制加法

2019-11-14 11:14:35
字體:
來源:轉載
供稿:網友

一、原題

Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100" 

一、中文

給定兩個二進制的字符串,返回它們的和,也是二進行制字符串。 

三、舉例

str1 = “111”,str2=“1”最后返回的結果的是1000

四、思路

先將對應的兩個二進制字符串轉換成對應的整數數組,從低位到高位進行相加,同時要考慮到最后相加還要擴展一位的情況。詳情請見代碼實現。

五、程序

package code;public class LeetCode42{		public static void main(String args[]){		String str = addBinary("111", "1");		System.out.PRintln(str);	}	//數組表示的數字進行加一操作,數組的最高位表示的是數字的最低位	public static String addBinary(String str1, String str2) {		if(str1 == null || str2 == null){			return null;		}else{			int num1[] = new int[str1.length()];			int num2[] = new int[str2.length()];						for(int i = 0; i < str1.length(); i++){				num1[i] = str1.charAt(i) - '0';			}						for(int j = 0; j < str2.length(); j++){				num2[j] = str2.charAt(j) - '0';			}						//使num1保存比較長的數組的長度	        if (num1.length < num2.length) {	            int[] tmp = num1;	            num1 = num2;	            num2 = tmp;	        }	        	        int index1 = num1.length - 1; // 字符數組ca最后一個索引下標	        int index2 = num2.length - 1; // 字符數組cb最后一個索引下標	        int carry = 0; // 下位的進位標識	        int result; // 加載的結果				        //將兩個數進行相加	        while (index1 >= 0 && index2 >= 0) {	            result = num1[index1] + num2[index2] + carry;	            num1[index1] = result % 2;	            carry = result / 2;	            index1--;	            index2--;	        }	        	        //處理num1剩余的數字,也就是較長的數字的剩余的數字	        while(index1 >= 0){	        	result = carry + num1[index1];	        	num1[index1] = result%2;	        	carry = result/2;	        		        	if(carry == 0){	        		break;	        	}	        	index1--;	        }	        	        // 將字符數組中的值轉換了字符的0或者1	        for (int i = 0; i < num1.length; i++) {	            num1[i] += '0';	        }	        	        // 不需要擴展一位	        if (carry == 0) {	            char[] ch = new char[num1.length];	            for (int i = 0; i < num1.length; i++) {	                ch[i] = (char) (num1[i]);	            }	            return new String(ch);	        }else{	            char[] ch = new char[num1.length + 1];	            ch[0] = '1';	            for (int i = 0; i < num1.length; i++) {	                ch[i + 1] = (char) (num1[i]);	            }	            return new String(ch);	        }	        		}		    }}	---------------------------------output----------------------------------
1000
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 涞源县| 岳阳市| 甘德县| 且末县| 汶上县| 满城县| 沙雅县| 玉林市| 富平县| 嘉黎县| 苍梧县| 唐海县| 金川县| 新河县| 斗六市| 沙田区| 山丹县| 偃师市| 保定市| 武夷山市| 延吉市| 漳州市| 观塘区| 崇文区| 大田县| 横山县| 冀州市| 尚义县| 太保市| 潜江市| 苍山县| 潜山县| 涞源县| 沾化县| 曲麻莱县| 临邑县| 梅河口市| 浠水县| 广东省| 房产| 宁蒗|