LeetCode OJ平台上Single Number II题目使用java位运算解决

5 篇文章 0 订阅

原题如下,不让用extra memory,那么哈希什么的就不要考虑了。

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?

在大神们的指导下,这个问题用java位运算就可以轻松解决。

如果某个数字出现三次,二进制格式下,三个数字的第0位相加%3==0,第1位相加%3==0,第......

所以把所有数字考虑成二进制格式,每一位相加,然后%3,结果就是只出现一次的数字了。

public class Solution {
    public static int singleNumber(int[] A) {
    	int l = A.length;
    	int result = 0;
    	int[ ] B = new int[32];
    	for(int i = 0; i < 32; i ++){
    		B[i] = 0;
    		for(int j = 0; j < l; j ++){
    			if(((A[j] >> i) & 1) == 1){
    				B[i] += 1;
    			}
    		}
    		B[i] %= 3;
    		result |= B[i] << i ;
    	}
    return result;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值