GXCPC2023 LowBit
One day Colin learned how to represent a number in binary form. For example,
the binary form of $(11){10}$ is $(1011){2}$ , and he was very excited!
Further, Eva taught Colin a well-known binary function $lowbit(x)$ which represents the value of the bit corresponding to the lowest $ 1 $ of $ x $ in binary form.
For example, $lowbit(11)=1$, $lowbit(4) = 4$
Colin thought this function was amazing, so he thought of an interesting problem, and then it comes:
Given a binary form of a number $x(x≤2^{10^5})$ , you need to perform some operations on $ x $.
Each turn you can choose one of the following two operations:
-
$ x+=lowbit(x) $ , which means adding the lowest bit of $x$ to $x$
-
$ x-=lowbit(x) $,which means subtracting the lowest bit of $x$ from $x$
-
Now Colin wants to know, what is the minimum number of operations required to turn $x$ into $0$?
输入
1100101
输出
4
分析
题目大意
- 使用+ - lowbit(x) ,最少多少次操作把 $x$到$0$
题解代码
如果右边的字符是 ‘0’,说明这是一个独立的 “1”,计数加一;
如果右边的字符也是 ‘1’,说明这是一个连续的 “11”,就将这个连续段的第一个 ‘1’ 改为 ‘0’,并将前面的 ‘1’ 变成 ‘0’,直到遇到一个 ‘0’ 为止,再将最后一个 ‘0’ 变成 ‘1’。然后回退一格继续扫描。
- 人话就是: 连续的111用 $+lowbit(x)$如果是单独是 0001000 用$-logbit(x)$
1 | import java.math.BigInteger; |