

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
First and Last Three Bits in C++
In this problem, we are given a number N. Our task is to find the decimal conversion of the fist three and last three bits for the given integer values N.
Let's take an example to understand the problem,
Input : 57 Output : 71
Solution Approach
A simple solution is by changing the number n into its binary equivalent and then saving the bits in an array. After this, we will convert the first three and last three values from the array into numbers individually. The decimal conversion of both the sets of bits is our result.
For example, take the number 80.
The binary conversion of 80 is 1010000.
The decimal conversion of the first three bits (101) is 5.
The decimal equivalent of the last three bits (000) is 0.
Hence the output is 5 0.
Example
Program to illustrate the working of our solution
#include <bits/stdc++.h> using namespace std; void convtbnTodcml(int n) { int arr[64] = { 0 }; int x = 0, index; for (index = 0; n > 0; index++) { arr[index] = n % 2; n /= 2; } x = (index < 3) ? 3 : index; int d = 0, p = 0; for (int index = x - 3; index < x; index++) d += arr[index] * pow(2, p++); cout << d << " "; d = 0; p = 0; for (int index = 0; index < 3; index++) d += arr[index] * pow(2, p++); cout << d; } int main() { int n = 57; cout<<"Decimal conversion of first and last bits of the number "<<n<<" is "; convtbnTodcml(n); return 0; }
Output
Decimal conversion of first and last bits of the number 57 is 7 1
- Related Questions & Answers
- Print numbers having first and last bits as the only set bits
- Check whether the number has only first and last bits set in Python
- Find the Number of quadruples where the first three terms are in AP and last three terms are in GP using C++
- Write a program in Python to print the first and last three days from a given time series data
- Get first and last elements from Java LinkedList
- Split First name and Last name using JavaScript?
- Get first and last elements from Vector in Java
- First element and last element in a JavaScript array?
- Delete first and last element from a LinkedList in Java
- Get all rows apart from first and last in MySQL
- Count numbers with same first and last digits in C++
- Get first and last elements of a list in Python
- Count substrings with same first and last characters in C++
- Get the first and last date of next month in MySQL?
- First and last child node of a specific node in JavaScript?
Advertisements