当前位置:网站首页>[algorithm] sword finger offer2 golang interview question 2: binary addition

[algorithm] sword finger offer2 golang interview question 2: binary addition

2022-07-06 12:50:00 Deng Jiawen jarvan

[ Algorithm ] The finger of the sword offer2 golang Interview questions 2: Binary addition

subject 1:

Given two 01 character string a and b , Please calculate their sum , And output... In the form of binary string .

Input is Non empty String and contains only numbers 1 and 0.

Example 1:

Input : a = “11”, b = “10”
Output : “101”
Example 2:

Input : a = “1010”, b = “1011”
Output : “10101”

Tips :

Each string consists only of characters ‘0’ or ‘1’ form .
1 <= a.length, b.length <= 10^4
If the string is not “0” , No leading zeros .

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/JFETK5
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Ideas 1: Analog binary addition

Analog binary addition time complexity O(n)

Code


func addBinary(a string, b string) string {
    
	// Ideas :  Analog binary computing 
	length := len(a)
	if len(b) > len(a) {
    
		length = len(b)
	}
	// Construct returns 
	resBs := make([]byte, length)
	// Pointer pointing from back to front 
	aP, bP := len(a)-1, len(b)-1
	// Carry or not 
	up := 0
	for i := len(resBs) - 1; i >= 0; i-- {
    
		var aByte byte = '0'
		var bByte byte = '0'
		if aP >= 0 {
    
			aByte = a[aP]
			aP--
		}
		if bP >= 0 {
    
			bByte = b[bP]
			bP--
		}
		//  Number of Statistics 
		count1 := 0
		if aByte == '1' {
    
			count1++
		}
		if bByte == '1' {
    
			count1++
		}
		count1 += up
		// Determine the current value and by the number up
		if count1 == 0 {
    
			up = 0
			resBs[i] = '0'
		} else if count1 == 1 {
    
			up = 0
			resBs[i] = '1'
		} else if count1 == 2 {
    
			up = 1
			resBs[i] = '0'
		} else {
    
			up = 1
			resBs[i] = '1'
		}
	}
	// final up
	res := string(resBs)
	if up == 1 {
    
		res = "1" + res
	}
	return res
}

test

 Insert picture description here

原网站

版权声明
本文为[Deng Jiawen jarvan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060914098099.html