Leetcode-SingleNumberII
来源:互联网 发布:爱之谷商城源码 编辑:程序博客网 时间:2024/06/06 02:46
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?
public class SingleNumberII {public int singleNumberII(int A[]){int bitInt[] = new int[32];//给数组初始化for (int i = 0; i<32; i++){bitInt[i] = 0;} int result=0; for(int i=0; i<32; i++){ for(int j=0; j<A.length; j++){ bitInt[i]+=(A[j]>>i)&1; } result|=(bitInt[i]%3)<<i; } return result; }}
Junit单元测试:
public class SingleNumberIITest {SingleNumberII s;@Beforepublic void setUp() throws Exception {}@Afterpublic void tearDown() throws Exception {}@Testpublic void testSingleNumberII() {s = new SingleNumberII();//int B[] = {43,16,45,89,45,-2147483648,45,2147483646,-2147483647,-2147483648,43,2147483647,-2147483646,-2147483648,89,-2147483646,89,-2147483646,-2147483647,2147483646,-2147483647,16,16,2147483646,43};int B[] = {-1,2,2,2};int result = s.singleNumberII(B);//assertEquals(2147483647, result);assertEquals(-1,result);//fail("Not yet implemented");}}
说明:这种方法是一种通用的解决方法;
知识:左移、右移i位的含义(正负数相同);
&与|跟左移、右移的结合使用;
难点:考虑到输入数据有负数的情况。
0 0
- Leetcode-SingleNumberII
- SingleNumberII
- SingleNumberII
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- 《Python 核心编程》(第二版) 例3.1
- 面试题19 二叉树的镜像
- XIB使用技巧
- UVA10780 - Again Prime? No Time.(分解质因子)
- 即将来到: CSS Feature Queries (CSS特性查询)
- Leetcode-SingleNumberII
- 移动互联网下的游戏变革
- Array.prototype.filter()
- Oracle 中connect by prior
- log4j详解与实战
- Moving Portraits
- 注册删除Tomcat为windows系统服务
- C# 利用QRCode生成二维码图片
- Tiny640触摸屏移植 + qt库移植