[英]Swap two integers without using a third variable
I have an assignment in which I need to swap two integers without using third variable. 我有一个赋值,我需要在不使用第三个变量的情况下交换两个整数。 I'm not sure how to do this.
我不知道该怎么做。 How would I code this?
我该如何编码呢?
Yes, it's possible: 是的,这是可能的:
Dim var1 = 1
Dim var2 = 2
var1 = var1 + var2
var2 = var1 - var2
var1 = var1 - var2
But why do you need it? 但你为什么需要呢? The code becomes abstruse.
代码变得深奥。
Lets assume 让我们假设
a = 10;
b = 20;
a = a + b; // a = 30
b = a - b; // b = 10
a = a - b; // a = 20
Values swapped. 交换价值。
Read up on the " xor swap algorithm ." 阅读“ xor交换算法” 。
You can find an answer here: 你可以在这里找到答案:
http://www.java2s.com/Tutorial/VB/0040__Data-Type/Swaptwointegerswithoutusingathird.htm http://www.java2s.com/Tutorial/VB/0040__Data-Type/Swaptwointegerswithoutusingathird.htm
firstValue = firstValue Xor secondValue
secondValue = firstValue Xor secondValue
firstValue = firstValue Xor secondValue
Dim a As Integer
Dim b As Integer
a= 1
b= 2
a = a Xor b
b = a Xor b
a = a Xor b
To swap two numeric variables do like this 要交换两个数字变量,请执行此操作
a = a + b;
b = a - b;
a = a - b;
OR 要么
a = a xor b;
b = a xor b;
a = a xor b;
where a and b are variables to be swapped 其中a和b是要交换的变量
theoretically 3 ways 理论上有3种方式
a = 4 , b = 5
1. Using XOR 1.使用XOR
a = a XOR b = 4 XOR 5 = 9
b = a XOR b = 9 XOR 5 = 4
a = a XOR b = 9 XOR 4 = 5
2. Using +,- 2.使用+, -
a = a+b = 4+5 = 9 // should not overflow
b = a-b = 9-5 = 4
a = a-b = 9-4 = 5
3. Using *,/ 3.使用*,/
a = a*b = 4*5 = 20 // should not overflow
b = a/b = 20/5 = 4 // should not overflow and should not be irrational number
a = a/b = 20/4 = 5 // should not overflow and should not be irrational number
The Xor or a+b algorithms above work and are the best way to do this, but just an example of a weird way to do it. 上面的Xor或a + b算法是最好的方法,但这只是一种奇怪的方法。 Still not sure why you would want to do this.
仍然不确定你为什么要这样做。 Just build a function that you supply two values ByRef and have it do the standard swap method.
只需构建一个函数,您可以提供两个值ByRef并让它执行标准交换方法。
Dim newList as New List(Of Integer)
newList.Add firstvalue
newList.Add secondValue
newList.Reverse
secondValue = newList.Item(0)
firstValue = newList.Item(1)
Take two text boxes and a command box.In command box type this code.
text1.text=val(text1.text) + val(text2.text)
text2.text=val(text1.text) - val(text2.text)
text1.text=val(text1.text) - val(text2.text)
Check link written for you 检查为您编写的链接
Approach#1. 方法一。
Addition and Subtraction Method 加法和减法
Integer a, b
read a and b
a= a+b;
b=a-b;
a=a-b;
Problem: 问题:
Incorrect result when sum of numbers will exceed the Integer range. 当数字总和超过整数范围时,结果不正确。
Approach#2. 方法2。
Multiplication and Division Method 乘法和除法
Integer a, b
read a and b
a=a*b;
b=a/b;
a=a/b;
Problems: 问题:
Approach#3. 方法3。
XOR Method 异或方法
Integer a , b
read a and b
a=a^b;
b=a^b;
a=a^b;
Best approach to solve this problem without any pitfalls. 解决这个问题的最佳方法,没有任何陷阱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.