I saw this in an interview preparation book - Algorithms for Interviews. It did not say what the answer was.
Based on my knowledge it does return false. Am I missing something ?
Because True is equal to 1 and False is equal to 0 , adding Booleans together is a quick way to count the number of True values.
In Python 3. x True and False are keywords and will always be equal to 1 and 0 .
Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true. For strings, empty strings are false and non-empty strings are true.
Javascript comes to my mind, it has a special number value Infinity
.
So this in fact will return true:
var x = Infinity;
alert(x == x + 1);
With integers, x != x + 1
for all x. With floating-point numbers, it's not guaranteed to be true; with a large enough exponent the 1 will fade into insignificance and be lost off the end of the mantissa - the easiest case to see from being the largest possible exponent which makes the value infinity. And infinity plus one is infinity. But it would work with smaller exponents as well.
Then in languages that support operator overloading it's quite possible to break such trivial mathematical laws. For example, in Python,
>>> class X(object):
... def __eq__(self, other):
... return True
... def __add__(self, other):
... return self
...
>>> x = X()
>>> x == x + 1
True
Unless the type (and implementation) is specified in the question, it is not safe to assume that it is always true. But as it has been specified that it's an integer, you can know that x != x + 1
for all x. Integers are stored as a series of bits and adding one is done by toggling the last bit and then carrying if it had been 1 et cetera, which will never get the same result (regardless of how many bits there are in the integer type, provided it's greater than zero).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With