
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Number Is Power of 2 in Go
Examples
Consider n = 16(00010000)
Now find x = n-1 => 15(00001111) => x & n => 0
Approach to solve this problem
Step 1 − Define a method, where n and is an argument, returns type is int.
Step 2 − Perform x = n & n-1.
Step 3 − If x is 0, then the given number is power of 2; else not.
Example
package main import ( "fmt" "strconv" ) func CheckNumberPowerOfTwo(n int) int { return n & (n-1) } func main(){ var n = 16 fmt.Printf("Binary of %d is: %s.\n", n, strconv.FormatInt(int64(n), 2)) flag := CheckNumberPowerOfTwo(n) if flag == 0{ fmt.Printf("Given %d number is the power of 2.\n", n) } else { fmt.Printf("Given %d number is not the power of 2.\n", n) } }
Output
Binary of 16 is: 10000. Given 16 number is the power of 2.
Advertisements