C++ Program to Find the One’s Complement of Positive Integer

«
»
This C++ Program which prints the 1’s complement of a positive integer. The program takes a number as the input and determines the each bit of the binary form of the number using a recursive function which is given the number as the parameter and negates it.

The function saves the remainder of the division of the number with 2, calls the same function with the quotient generated after division, the number is negated and printed after the number drops to less than equal to one and then the stack created due to recursion is unwind.

Here is source code of the C++ program which prints the 1’s complement of a positive integer. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Print the 1's Complement of an Integer
  3.  */
  4.  
  5. #include<iostream>
  6. using namespace std;
  7.  
  8. void onescomp(int num)
  9. {
  10.     int rem;
  11.  
  12.     if (num <= 1)
  13.     {
  14.         cout << !num;
  15.         return;
  16.     }
  17.     rem = num % 2;
  18.     onescomp(num / 2);
  19.     cout << !rem;
  20. }
  21.  
  22. int main()
  23. {
  24.     int dec, bin;
  25.     cout << "Enter the number : ";
  26.     cin >> dec;
  27.  
  28.     if (dec < 0)
  29.         cout << dec << " is not a positive integer." << endl;
  30.     else
  31.     {
  32.         cout << "The ones complement form of " << dec << " is ";
  33.         onescomp(dec);
  34.         cout << endl;
  35.     }
  36.     return 0;
  37. }

$ g++ main.cpp
$ ./a.out
Enter the number : 10
The ones complement form of 10 is 0101

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.