How do I eliminate the ternary operator from the code below? I’m looking for something using only integer operators (shifts, additions, etc).
a = (a < 0) ? (-a * 2) - 1 : (a * 2)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Off the top of my head, assuming
ais anint:>>is arithmetic (signed) shift left. Soa>>31replaces all the bits with the sign bit. All bits set gives -1. Multiple by two and add one, negatives go to -1 and positives (and zero) to 1.>>>is logical (unsigned) shift left. Soa>>>31clears the top 31 bits and places the sign bit in bit 0 (0 for positive numbers and zero; 1 for negative numbers).The “proper” way of doing something vaguely like this is: