Java交换数据的方法

    技术2022-07-17  80

    题目

    实现x与y的数据交换

    方法一:第三方变量

    class jh{ public static void main(String[] args){ int x=10,y=5; int temp; temp=x; x=y; y=temp; System.out.println("x="+x+",y="+y); } }

    方法二:数学换算

    class jh{ public static void main(String[] args){ int x=10,y=5; x=x+y //x=10+5=15 y=x-y //y=15-5=10 x=x-y //x=15-10=5 System.out.println("x="+x+",y="+y); } }

    方法三:异或运算

    异或运算符特点 相同为0,不同为1; ^运算:一个数据对另一个数据异或两次,本数不变 例如: 10^ 5^ 5. 10=1010, 5=0101 10^ 5=1111 1111^0101=1010 最后为10

    class jh{ public static void main(String[] args){ int x=10,y=5; x=x^y; //x=10^5 y=x^y; //y=10^5^5=10 x=x^y; //x=10^5^10=5 System.out.println("x="+x+",y="+y); } }
    Processed: 0.011, SQL: 9