Single Number III in C++

C++Server Side ProgrammingProgramming

Suppose we have an array, there exactly two elements appear once, but others are appearing twice. So we have to define a function, that will find these two numbers. So if the given array is like [1,2,3,1,5,2], then the output will be [3, 5].

To solve this, we will follow these steps −

  • xor_res := 0

  • for i in range 0 to size of nums

    • xor_res := xor_res XOR nums[i]

  • pos := 0

  • while xor_res AND 2^pos = 0, do,

    • increase pos by 1

  • num1 := 0

  • for i in range 0 to size of nums – 1

    • if nums[i] and 2 ^ pos is not 0, then

      • num1 := num1 XOR num[i]

  • num2 := xor_res XOR num1

  • return num1 and num2

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector <int> singleNumber(vector<int>& nums) {
      int xor_result = 0;
      for (int i=0;i < nums.size(); i++) {
         xor_result = xor_result ^ nums[i];
      }
      int pos = 0;
      while ((xor_result & (1 << pos)) == 0) {
         pos++;
      }
      int num1 = 0;
      for (int i=0;i < nums.size(); i++) {
         if ((nums[i] & (1 << pos)) != 0) {
            num1 = num1 ^ nums[i];
         }
      }
      int num2 = xor_result ^ num1;
      vector<int> result = {num1, num2};
      return result;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,1,3,2,5};
   print_vector(ob.singleNumber(v));
}

Input

[1,2,1,3,2,5]

Output

[3, 5, ]
raja
Published on 02-May-2020 10:52:38
Advertisements