Signed Binary Expansion
Time limit1sMemory limit128 MB
Given a decimal integer with up to 500 digits, find the smallest possible count of nonzero digits in a signed binary expansion.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Greedy, Math, Bit manipulation
- Solved
- No attempts yet
Problem
A binary expansion of an integer is a sequence of "digits" that satisfies all three of the following conditions:
- every digit is equal to , , or ;
- the most significant digit is not zero;
- .
A single integer can have many different binary expansions. Among all of them, the ones with the fewest nonzero digits are called optimal. For example, writing as for convenience, the binary expansions of include , , and . The first one, , has only nonzero digits, so it is an optimal expansion of .
Write a program that, given an integer , computes the number of nonzero digits in its optimal binary expansion.
Input
The first line contains an integer (). The second line contains an integer made up of decimal digits. The number is written starting from its most significant digit (that is, in the usual order) and begins with a nonzero digit.
Output
Print, on a single line, the number of nonzero digits in the optimal binary expansion of .