DEV Community

loading...

Discussion on: Coding Puzzles: Week of 4/8

Collapse
joshuagilless profile image
Joshua Gilless

Thanks for this! I don't really know C++, but I figured I'd give it a shot:

int stray(std::vector<int> numbers) {
    int n1, n2, n3;
    for (int i = 2; i < numbers.size(); i++) {
      n1 = numbers[i];
      n2 = numbers[i - 1];
      n3 = numbers[i - 2];
      if (n1 == n2 && n1 != n3) {
        return n3;
      } else if (n1 == n3 && n1 != n2) {
        return n2;
      } else if (n1 != n2 && n2 == n3) {
        return n1;
      }
    }
};
Collapse
joshuagilless profile image
Joshua Gilless • Edited

@laurieontech did something really cool in JS with a bitwise XOR (her answer is above), so I figured I'd update this C++ answer with a bitwise XOR since I love it!

int stray(std::vector<int> numbers) {
    int r = numbers[0];
    for (int i = 1; i < numbers.size(); i++)
    {
        r ^= numbers[i];
    }
    return r;
};