IT技术杂谈

When you are about to give up think of that one reason why you wanted to start.

每日算法(4)——两个变量交换

1、算法思路

(1)利用中间变量交换数据
(2)两个数先进行求和,然后相减进行数据交换
(3)利用位运算的方式进行数据交换(一个数异或同一个数两次,结果还是那个数)

2、具体代码

package com.peter.algorithm.other;

import org.junit.Test;

public class VariablExchange {
    @Test
    public void test() {
        swapByTempVariable();
        swapBySum();
        swapByBitOperation();
    }

    //利用中间变量交换数据
    public static void swapByTempVariable() {
        int a = 3, b = 5;
        System.out.println("swapByTempVariable before exchange! a:" + a + " b:" + b);
        int temp = a;
        a = b;
        b = temp;
        System.out.println("swapByTempVariable after exchange! a:" + a + " b:" + b);
    }

    //两个数求和然后相减的方式进行数据交换
    private static void swapBySum() {
        int a = 3, b = 5;
        System.out.println("swapBySum before exchange! a:" + a + " b:" + b);
        a = a + b;
        b = a - b;
        a = a - b;
        System.out.println("swapBySum after exchange! a:" + a + " b:" + b);
    }

    //利用位运算的方式进行数据的交换(一个数异或同一个数两次,结果还是那个数)
    private static void swapByBitOperation() {
        int a = 3, b = 5;
        System.out.println("swapByBitOperation before exchange! a:" + a + " b:" + b);
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;
        System.out.println("swapByBitOperation after exchange! a:" + a + " b:" + b);
    }
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tju2015zc/article/details/79966850
文章标签: 变量交换
个人分类: 每日算法
上一篇每日算法(3)——素数
下一篇每日算法(5)——正整数分解质因数
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭