- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Golang Program to check whether given positive number is power of 2 or not, without using any branching or loop
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.
- Related Articles
- Write a Golang program to check whether a given number is prime number or not
- Write a Golang program to check whether a given number is a palindrome or not
- Golang Program to check a given number is finite or not
- Program to check whether given number is Narcissistic number or not in Python
- How to check whether a number is Positive or Negative in Golang?
- C program to Check Whether a Number is Positive or Negative or Zero?
- Java Program to Check Whether a Number is Positive or Negative
- Haskell Program to Check Whether a Number is Positive or Negative
- C++ Program to Check Whether a Number is Positive or Negative
- Program to check whether the given number is Buzz Number or not in C++
- Check whether a given number is Polydivisible or Not
- JavaScript program to check whether a given number is power of 2
- Write a Golang program to check whether a given array is sorted or not (Using Bubble Sort Technique)
- 8085 program to check whether the given 16 bit number is palindrome or not
- C++ program to check whether given string is bad or not

Advertisements