zoukankan      html  css  js  c++  java
  • 交换两个变量的值

    1、方案一

     1 public static void main(String[] args) {
     2     int x = 1;
     3     int y = 2;
     4         
     5     /*
     6         通用的方案:适用于任意的数据类型借助于第三个通样类型的临时变量
     7     */
     8     int temp = x;//x变量中值就赋值给了temp  temp = 1
     9     x = y;//再把y中的值放到x中,x = 2
    10     y = temp;//再把temp中的值赋值给y  y=1
    11     System.out.println("x = " + x);
    12     System.out.println("y = " + y);
    13 }        

    2、方案二

     1 public static void main(String[] args){
     2     int x = 1;
     3     int y = 2;
     4     /*
     5     方案二:只适用于int等整数类型
     6     */
     7     x = x ^ y;
     8     y = x ^ y;//(新的x) ^ 原来的y = (原来的x ^ 原来的y) ^ 原来的y = 原来的x  (求不同)
     9     x = x ^ y;//(新的x) ^ 新的y = (原来的x ^ 原来的y) ^ 原来的x = 原来的y
    10     System.out.println("x = " + x);
    11     System.out.println("y = " + y);
    12 
    13 }

    3、方案三

     1 public static void main(String[] args){
     2     int x = 1;
     3     int y = 2;
     4     /*
     5     方案三:只适用于int等整数类型有风险,可能会溢出
     6     */
     7     x = x + y;//有风险,可能会溢出
     8     y = x - y;//(新的x) - 原来的y = (原来的x + 原来的y)- 原来的y  = 原来的x
     9     x = x - y;//(新的x) - 新的y = (原来的x + 原来的y) - 原来的x = 原来的y
    10     System.out.println("x = " + x);
    11     System.out.println("y = " + y);
    12 }
  • 相关阅读:
    Spring学习笔记
    Bash编程(6) String操作
    Bash编程(5) Shell方法
    Bash编程(4) 参数与变量
    Bash编程(2) 循环与分支
    CentOS 升级 openSSH
    Bash编程(1) 基础
    DNS配置
    资料收集:学习 Linux/*BSD/Unix 的 30 个最佳在线文档
    【数位DP】[LOJ10168] 恨7不成妻
  • 原文地址:https://www.cnblogs.com/niujifei/p/11834067.html
Copyright © 2011-2022 走看看