publicclassSwapTwoNumbers{ staticclassMyInteger{ privateint a; publicMyInteger(int a){ this.a = a; } publicintgetValue(){ return a; } publicvoidchangeValue(int a){ this.a = a; } } publicstaticvoidswap(MyInteger a, MyInteger b){ int t = a.getValue(); a.changeValue(b.getValue()); b.changeValue(t); } publicstaticvoidmain(String[] args){ MyInteger a = new MyInteger(4); MyInteger b = new MyInteger(10); System.out.println("a is "+a.getValue()+" and b is "+b.getValue()); swap(a, b); System.out.println("a is "+a.getValue()+" and b is "+b.getValue()); } }
方案2:利用main所在的类本身
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicclasst1{ int a, b; publict1(int a, int b){ this.a = a; this.b = b; } publicvoidswap(){ int t = a; a = b; b = t; } publicstaticvoidmain(String[] args){ t1 x = new t1(3,4); System.out.println("a is "+x.a+" and b is "+x.b); x.swap(); System.out.println("a is "+x.a+" and b is "+x.b); } }
方案3:利用数组
1 2 3 4 5
publicstaticvoidswap(int[] data, int a, int b){ int t = data[a]; data[a] = data[b]; data[b] = t; }
Part2
求gcd。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import java.util.Random;
publicclasst1{ publicstaticintgcd(int a, int b){ //if(a <= 0 || b <= 0) return 0; if(a%b==0) return b; return gcd(b, a%b); } publicstaticvoidmain(String[] args){ Random r = new Random(); int a = r.nextInt(), b = r.nextInt(); a=Math.abs(a); b=Math.abs(b); System.out.println(a+" "+b); if(a<b) System.out.println(gcd(b,a)); else System.out.println(gcd(a,b)); } }