您的位置:首页 > 编程语言

【ylchou】通过代码完成2个整数内容的交换

2016-11-14 12:50 190 查看
通过代码完成2个整数内容的交换

不磨叽了,直接上代码:

[java] view plain copy

package com.hylink.common;

public class Swap {

/**

* @function 2个整数内容交换

* @author ylchou@qq.com

* @param args

*/

public static void main(String[] args) {

//method one 不用额外的变量来交换,不过可能回溢出

int i = 23;

int j = 55;

System.out.println("i,j:"+i+","+j);

i = i + j;//右边为i和j之和 可能回溢出

j = i - j;//右边为为i的值

i = i - j;//右边为j的值

System.out.println("i,j:"+i+","+j);

//method two 用额外的变量来临时存储交换,不会发生溢出

int x = 44;

int y = 77;

System.out.println("x,y:" + x + "," + y);

int tmp = 0;

tmp = x;

x = y;

y = tmp;

tmp = 0;

System.out.println("x,y:" + x + "," + y);

System.out.println(tmp);

}

}

console print:

i,j:23,55

i,j:55,23

x,y:44,77

x,y:77,44

0

----------------------------------------------------------------------------------------

扩展:要是字符串交换,用method two,示例如下:

[java] view plain copy

package com.hylink.common;

public class Swap {

/**

* @function 字符串内容交换

* @author ylchou@qq.com

* @param args

*/

public static void main(String[] args) {

//字符串交换 用额外的变量来临时存储交换

String str3 = "abc";

String str4 = "xyz";

System.out.println("str3,str4:"+str3+","+str4);

String tmpStr = null;

tmpStr = str3;

str3 = str4;

str4 = tmpStr;

tmpStr = null;

System.out.println("str3,str4:"+str3+","+str4);

System.out.println(tmpStr);

}

}

console print:

str3,str4:abc,xyz

str3,str4:xyz,abc

null
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  习题
相关文章推荐