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

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

问题描述

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

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);

你能改进吗?

问题是问如何在保持清晰度的同时用最少的字符写出上述语句 - 这怎么能不是一个真正的问题"?这并非旨在成为高尔夫代码练习,尽管人们将其视为高尔夫,但已经得出了一些有趣的答案 - 很高兴看到以建设性和发人深省的方式使用高尔夫.

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.

推荐答案

你可以简单地使用:

v = 1 - v;

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

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;

要清楚;我从来没有像代码高尔夫一样处理这个问题,只是为了找到一种简单的方法来完成任务,而不使用任何像操作符的副作用这样的模糊技巧.

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天全站免登陆