Problem1
来源:互联网 发布:软件学报审稿流程 编辑:程序博客网 时间:2024/04/25 08:46
The Problem:
Presented with the integer n, find the 0-based position of the second rightmost zero bit in its binary representation (it is guaranteed that such a bit exists), counting from right to left.
Return the value of
Example
For n = 37, the output should be secondRightmostZeroBit(n)= 8.
3710 = 100101
Thus, the answer is
Input/Output
- [time limit] 4000ms (py)
- [input] integer n Constraints:
4 ≤ n ≤230 . - [output] integer
The Solution:
int secondRightmostZeroBit(int n) { return -~((n-~(n^(n+1))/2)^(n-~(n^(n+1))/2+1))/2 ;}
The Explanation:
To find second rightmost zero bit, we first need to find the first one. (in other words, Least significant zero bit).
How to…
Let’s look at the alternatives that we can use.
^
If we use XOR between our number N and (N+1), we get
This looks good. If we get the complement of this.
We can divide it by two to shift it (or use >> operator to shift it one bit.)
what we have is XOR and then a complement operation, namely, XNOR. (We don’t have XNOR, so we need to produce it ourselves.
a XNOR b = ~(a ^ b)
Now,
We found our first zero. What do we do to find second?
If we sum up our original number with this result, we get rid of first zero. (note the complement operation makes the number negative, so we need to subtract it instead of summation.
n-~(n^(n+1))/2
this is equal to
Now, if we do the same thing operation with this new number, we get our result.
CodeFights limits us to write it as one return statement. So, it looks more complicated.
But if we assign this to a new variable x.
We have
-~(x^(x+1))/2
As our answer.
Otherwise, just type it twice and get the result.
Note that this time we don’t subtract it from X. Because we only need the number, we don’t need to get rid of the zero.
- Problem1
- Problem1
- snort problem1
- Problem1:twoSum
- problem1——2
- NOIP 2011 Day1 Problem1
- NOIP 2011 Day2 Problem1
- node.js Problem1
- Unit6--problem1.1--悦
- Unit6--problem1.2--悦
- Unit--problem1.3--悦
- leetcode Problem1 two sum
- Project Euler Problem1
- Project Euler Problem1-5
- c++11多线程-problem1
- Debug C++ in VS2010: problem1
- SOJ--4393: LaoB's problem1
- [USACO2015February,Bronze] Problem1.Censoring(Bronze)
- Linux学习总结01——内存管理——基本概念篇
- boolan web Ex笔记二
- Android数据存储五种方式总结
- Redis pub/sub(Publish,Subscribe)
- peU盘ud区和efi区如何共用wim文件
- Problem1
- 二叉树的遍历
- java多线程
- 性能优化之数据存储&DOM编程
- Qt之格栅布局(QGridLayout)
- 关于scanf、getchar的用法解析
- 学习总结(一)
- jzoj4064 JSOI2015 套娃 [贪心]
- 第二章回顾