Advertisement
janac

Change 1 -> 0 no conditionals, negation, bit operators

Jan 4th, 2022
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1.  
  2.  
  3. // Change 0 to 1 or 1 to 0.
  4. // Not allowed: conditionals, booleans, bit operators
  5.  
  6. #include <iostream>
  7. #include <cctype>
  8. #include <string>
  9.  
  10. using namespace std;
  11.  
  12. // This function changes a 0 to a 1 or
  13. // a 1 to a 0, without using
  14. // conditionals, negation or bit operators
  15. int flip(int zero_or_one)
  16. {
  17.     int flipped_number = 0; // The result of the flip.
  18.  
  19.     flipped_number = 1 - zero_or_one; // Flip the number.
  20.     return flipped_number; // Return the result.
  21. }
  22.  
  23. int main()
  24. {
  25.     string one_or_zero; // User input.
  26.     int result = 0; // Output after flip.
  27.  
  28.     cout << "Enter 1, and you will receive 0.\n"
  29.         "Enter 0, and you will receive 1.\n"
  30.         "Your entry: ";
  31.     getline(cin, one_or_zero); // Get user input.
  32.     // If the user did not enter a 1 or a 0,
  33.     while (one_or_zero.compare("0") != 0 && one_or_zero.compare("1") != 0)                
  34.     {
  35.         cout << "You must enter 1 or 0.\n"
  36.             "Your entry: ";
  37.         cin >> one_or_zero; // Get new input.
  38.     }
  39.  
  40.     result = flip(stoi(one_or_zero)); // Flip the number.
  41.  
  42.     cout << result << '\n'; // Display the result.
  43.  
  44.     return 0; // End the program.
  45. }
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement