[Golang] Leetcode - 476. Complement of numbers

[Golang] Leetcode - 476. Complement of numbers

Topic : After inverting the binary representation of an integer (0 to 1, 1 to 0), and then converting it to a decimal representation, the complement of this integer can be obtained.

For example, the binary representation of the integer 5 is "101", which is reversed to obtain "010", and converted back to the decimal representation to obtain 2's complement.
Given an integer num, output its complement.

Link : Leetcode - 476. Complement of numbers .

Example 1:

Input: num = 5
Output: 2
Explanation: The binary representation of 5 is 101 (without leading zero), and its complement is 010. So you need to output 2.

Example 2:

Input: num = 1
Output: 0
Explanation: The binary representation of 1 is 1 (without leading zero bits), and its complement is 0. So you need to output 0.

Idea: First convert the input number to binary, then directly invert each digit after conversion, and then convert to decimal. During the period, pay attention to multiplying the value of the exponent n in 2 ^ n (n is the exponent) when converting binary to decimal. If the exponent is understood, the problem will be solved.

Go code:

package main

import (
	"fmt"
	"math"
)

func findComplement(num int) int {
    
    
	var sum, dealer, remainder int
	var count float64
	for num > 0 {
    
    
		dealer = num / 2
		// 求余数
		remainder = num % 2
		// 求余数补数
		if remainder == 1 {
    
    
			remainder = 0
		} else {
    
    
			remainder = 1
		}
		// 直接转化为 10 进制
		mid := int(math.Pow(2, count))
		sum = remainder*mid + sum
		// 位数 +1 ,也就是后面乘以 2 的指数
		count += 1
		// 商返回重新循环
		num = dealer
	}
	return sum
}
func main() {
    
    
	fmt.Println(findComplement(5))
}

Submit a screenshot:

insert image description here

Guess you like

Origin blog.csdn.net/a6661314/article/details/125698032