Write a program to find One's complement of a number
Example 1:
Input: num=8
Output:7
Approach:
Java
public class OnesComplement {public static void main(String[] args) {int num = 8;int onesComp = oneComplement(num);System.out.println("One's complement is " + onesComp);}private static int oneComplement(int num) {int n = num;int length = 0;// find the no of bits// in binary form of a numberwhile (n > 0) {length++;n = n / 2;}int power = (int) (Math.pow(2, length) - 1);// formaula = (pow(2,lenght)-1)^numint complement = power ^ num;// return one's complementreturn complement;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the//one's complement of a numberint oneComplement(int num){int n=num;int length=0;//find the no of bits//in binary form a numberwhile(n>0){length++;n=n/2;}int power=pow(2,length)-1;//formaula = (pow(2,lenght)-1)^numint complement=power^num;//return one's complementreturn complement;}int main(){//inout numberint num=8;int complement=oneComplement(num);cout<<"One's Complement is ";cout<<complement<<"\n";return 0;}
No comments:
Post a Comment