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.
can you provide source?
I tried to find this question on online judges, but was not able to find any
I doubt this is from an OA. Also not a hard problem for an expert atleast.
Can you please suggest how to solve this in optimal complexity?
Sorry but I unintentionally don't want to help in an ongoing OA. I would answer this after awhile.
Its not a running OA, i heard it from my friends , and we had our OAS's last year, also have edited the question, decimal thing is easy , we need the string representation,
What? This problem doesn't make sense then. Why do you specifically need string representation? I'm sure this isn't solvable for 1e5 length. You would have to use string multiplication and addition and surely that will take quite alot of time. 2^60 is around 1e18, there's no need to guess how big 2^1e5 would be).
Auto comment: topic has been updated by expertcoderhk (previous revision, new revision, compare).
Final solution needs to be string not a decimal
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
Exactly what I did
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-significant1
, then we can remove that-1
. Then just repeat until there are no more negatives. For example:This is pretty straightforward to implement in linear time:
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.