无需重写条件语句或运营商件C code的? [英] Rewriting a piece of C code without conditional statements or operators?

查看:122
本文介绍了无需重写条件语句或运营商件C code的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是在技术面试,其中面试官给了我一张code这样

I was in a technical interview where the interviewer gave me a piece of code like this

  int a=1;
  a++;
  ...something..
  ...something.
  if(a==25)
   a=0;

他说,如果其他人或三元运营商如果条件我重写这个code,而不使用开关。如何可以做到?

he said me to rewrite this code without using switch,if else or ternary operator for the if condition. How it can be done?

推荐答案

这是很简单的实际上是:

It's quite simple actually:

a *= (a != 25);

这将乘以0,如果等于25,否则它将被1乘以。

This will multiply a by 0 if a is equal to 25, else it will multiply a by 1.

如果你也不许测试相等那么这里是一个完全的算术方式:

If you're also not allowed to test for equality then here is a fully arithmetic way:

unsigned int v = a - 25;

/* test for bits set and put result in lsb of v */
v |= v >> 16;
v |= v >> 8;
v |= v >> 4;
v |= v >> 2;
v |= v >> 1;

/* set a to a if lsb of v is 1, else set to 0 */
a *= v & 1;

这篇关于无需重写条件语句或运营商件C code的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆