• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Single Number II

这题有点难,网上大神的这段代码太牛了。

 1 class Solution {
 2 public:
 3     int singleNumber(int A[], int n) {
 4         // Note: The Solution object is instantiated only once and is reused by each test case.
 5         int one = 0;
 6         int two = 0;
 7         int three = 0;
 8         for(int i = 0 ; i < n ; i++){
 9             two |= A[i] & one;
10             one = A[i] ^ one;
11             three = ~(one&two);
12             one &= three;
13             two &= three;
14         }
15         return one;
16     }
17 };

这段代码就很好理解

 1 class Solution {
 2 public:
 3     int singleNumber(int A[], int n) {
 4         int ans = 0;
 5         for (int i = 0; i < 32; ++i) {
 6             int count = 0;
 7             for (int j = 0; j < n; ++j) count += (A[j] >> i) & 1;
 8             ans |= ((count % 3 != 0) << i);
 9         }
10         return ans;
11     }
12 };

 C#

 1 public class Solution {
 2     public int SingleNumber(int[] nums) {
 3         int ans = 0;
 4         for (int i = 0; i < 32; i++) {
 5             int count = 0;
 6             for (int j = 0; j < nums.Length; j++) count += (nums[j] >> i) & 1;
 7             ans |= ((count % 3 != 0? 1 : 0) << i);
 8         }
 9         return ans;
10     }
11 }
View Code

 

posted @ 2014-01-13 14:10  ying_vincent  阅读(169)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3