---
title: "Single Number II "
author: "wadefall"
date: "2014-02-19T15:26:25Z"
tags: []
categories: ["编程语言"]
slug: "single-number-ii"
draft: false
lastmod: "2014-02-19T16:15:42Z"
id: 2019354
url: "https://wadefall.iteye.com/blog/2019354"
---

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

用one, two, three标记当前数出现一次、两次、三次。每处理一个数时分别计算与、异或、非，当前数字出现三个时前两个变量为1, 第3个变量为0;从而清除该数字;最后保留下来的one就是出现了一次的数字。


```c++

class Solution {
public:
    int singleNumber(int A[], int n) {
      int one = 0, two = 0, three = 0;

      for(int i = 0; i < n; ++i) {
	two |= one & A[i];
	one ^= A[i];
	three = ~(one & two);
	one &= three;
	two &= three;
      }
      return one;
    }
};


```