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 }
  • 相关阅读:
    IDEA 工具使用报错总结
    Struts2 值栈总结(ValueStack)
    hibernate 中映射关系配置
    Java 注解之总结
    ssh_整合总结
    Ajax 请求之_请求类型详解
    C++的重载赋值运算符
    vector容器使用reserve预留空间
    C++中的内存分配
    C++ const修饰指针
  • 原文地址:https://www.cnblogs.com/niujifei/p/11834067.html
Copyright © 2011-2022 走看看