Advertisement
beelzebielsk

isPowerTwo.cpp

Mar 13th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. bool isPowerTwo(int number) {
  2.     bool hasOne = false;
  3.     unsigned int current = number;
  4.     while (true) {
  5.         /* If the number was 0, then hasOne is false. Otherwise,
  6.          * hasOne is true, but since we are here, the number had only
  7.          * one bit as 1.  Thus the number is a power of two.
  8.          */
  9.         if (current == 0) return hasOne;
  10.         if ((current & 1) == 1) {
  11.             /* If a number has more than one bit as 1, then it is not
  12.              * a power of two.
  13.              */
  14.             if (hasOne) return false;
  15.             hasOne = true;
  16.         }
  17.         // Remove a bit.
  18.         current = current >> 1;
  19.     }
  20. }
  21.  
  22. vector <int> isPowerOf2(vector <int> nums) {
  23.     vector <int> answers = {};
  24.     for (int i = 0; i < nums.size(); i++) {
  25.         answers.push_back(isPowerTwo(nums[i]));
  26.     }
  27.     return answers;
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement