Блог пользователя expertcoderhk

Автор expertcoderhk, история, 3 года назад, По-английски

Given a binary string of length<=100000, where even index means positive power of 2 and odd index means negative power of 2, find the value of string in normal binary representation.Assume rightmost index is least significant power.

For e.g If string s="1011" will be equal to (2^0)*1-(2^1)*1+(2^2)*0-(2^3)*1 = -9 so represent -9 in binary reprsentation How to approach this question.

  • Проголосовать: нравится
  • -15
  • Проголосовать: не нравится

»
3 года назад, скрыть # |
 
Проголосовать: нравится +9 Проголосовать: не нравится

can you provide source?

»
3 года назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by expertcoderhk (previous revision, new revision, compare).

»
3 года назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Final solution needs to be string not a decimal

»
3 года назад, скрыть # |
 
Проголосовать: нравится +1 Проголосовать: не нравится

Correct me if I am wrong, the problem is equivalent to finding the difference between numbers in which even bits are set and in which odd bits are set. So if we are given a string 10110101, we can divide this string into two strings -> 10100000 (if odd bits are set in the original string set that bit in this string) and 00010101 (if odd bits are set in the original string set that bit in this string) and we can simply find the difference between these two strings

»
3 года назад, скрыть # |
 
Проголосовать: нравится +9 Проголосовать: не нравится

Consider the more general problem of converting any binary number with negative digits into a normal binary number.

Observe that a chain of the form (1)(0)(0)...(0)(0)(-1) becomes (0)(1)(1)...(1)(1)(1).

So if we find the most significant -1 and the nearest more-significant 1, then we can remove that -1. Then just repeat until there are no more negatives. For example:

1. +1   0  -1  -1   0  +1  -1   = 64 - 16 - 8 + 2 - 1 = 41
2.  0  +1  +1  -1   0  +1  -1
3.  0  +1   0  +1   0  +1  -1
4.  0  +1   0  +1   0   0  +1   = 32 + 8 + 1 = 41
result: 0101001

This is pretty straightforward to implement in linear time:

// a[0] is the least significant digit
// a[i] is one of {-1, 0, +1}
vector<int> solve(vector<int> a) {
    int j = int(a.size()); // position of the last +1 we have seen
    for (int i = int(a.size()) - 1; i >= 0; --i) {
        if (a[i] == 1) {
            j = i;
        } else if (a[i] == -1) {
            for (int k = i; k < j; ++k)
                a[i] = 1;
            a[j] = 0;
            j = i;
        }
    }
    return a;
}

It doesn't work if the most significant digit is -1 (i.e. when the number is negative) but this is easy to detect and you can just flip the sign of all the digits and handle the negative however you want.