I have a piece of code where I multiply two numbers but condition is none of those integer numbers should be 0. If it is 0, I need to make it to 1 so that it is not counted.
y=x*z // x>0, z>0. if x==0 then x=1, if z==0, then z=1;
I want to avoid "if" condition check on every variable and replace with 1. Is there a better way of doing it.
Refer an algorithm given below to replace all the 0's to 1 in an integer. Step 1 − Input the integer from the user. Step 2 − Traverse the integer digit by digit. Step 3 − If a '0' is encountered, replace it by '1'.
The idea is simple, we assign a variable 'temp' to 0, we get the last digit using mod operator '%'. If the digit is 0, we replace it with 5, otherwise, keep it as it is. Then we multiply the 'temp' with 10 and add the digit got by mod operation. After that, we divide the original number by 10 to get the other digits.
Below
y=(x==0?1:x)*(z==0?1:z)
will give you this [ assembly ] code.
and an adaption borrowed from @Jerry Coffin's comment to his [ answer ]
y=(x+(x==0))*(z+(z==0));
will give you this [ assembly ] code.
y = (!x ^ x) * (!z ^ z);
This works because when you xor a number with 0, you get the same number back. So if x != 0
, then !x == 0
, and !x ^ x
is equivalent to 0 ^ x
, which is x
. And if x == 0
, then !x == 1
, and !x ^ x
is equivalent to 1 ^ 0
, which is 1.
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