Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is most optimal way to replace integer '0' with '1' in c++

Tags:

c++

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.

like image 641
user437777 Avatar asked Jun 21 '16 05:06

user437777


People also ask

How to replace 0 with 1 in C?

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'.

How to replace 0's with 5's in a given integer not supposed to use string approach?

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.


2 Answers

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.

like image 200
sjsam Avatar answered Nov 09 '22 05:11

sjsam


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.

like image 23
Benjamin Lindley Avatar answered Nov 09 '22 05:11

Benjamin Lindley