是否有更好的写法v =(v == 0?1:0); [英] Is there a better way of writing v = (v == 0 ? 1 : 0);

查看:173
本文介绍了是否有更好的写法v =(v == 0?1:0);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在0和1之间切换一个变量。如果它为0,我想将其设置为1,否则如果是1,我要将其设置为0.



这是一个基本的操作,我经常写我想调查最短,最清晰的可能的方法。这是我到目前为止最好的:

  v =(v == 0?1:0);你能改进吗?



编辑:问题是要求如何用最少的字符写上述语句,同时保持清晰度 - 这不是一个真正的问题?这不是一个代码高尔夫练习,虽然一些有趣的答案已经出来的人接近它作为高尔夫 - 很高兴看到高尔夫以一种建设性和发人深省的方式使用。

解决方案

您可以直接使用:

  v = 1 -  v; 

这当然假定变量被正确初始化,即它只有值0或1



另一种方法较短,但使用较不常用的运算符:

  v ^ = 1; 



编辑:



我从来没有把这个问题作为代码高尔夫,只是为了找到一个简单的方法来完成这个任务,而不使用任何模糊的技巧,如操作符的副作用。


I want to toggle a variable between 0 and 1. If it's 0 I want to set it to 1, else if it's 1 I want to set it to 0.

This is such a fundamental operation that I write so often I'd like to investigate the shortest, clearest possible way of doing it. Here's my best so far:

v = (v == 0 ? 1 : 0);

Can you improve on this?

Edit: the question is asking how to write the above statement in the fewest characters while retaining clarity - how is this 'not a real question'? This wasn't intended to be a code-golf exercise, though some interesting answers have come out of people approaching it as golf - it's nice to see golf being used in a constructive and thought-provoking manner.

解决方案

You can simply use:

v = 1 - v;

This of course assumes that the variable is initialised properly, i.e. that it only has the value 0 or 1.

Another method that is shorter but uses a less common operator:

v ^= 1;

Edit:

To be clear; I never approached this question as code golf, just to find a short way of doing the task without using any obscuring tricks like side effects of operators.

这篇关于是否有更好的写法v =(v == 0?1:0);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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