题目2与3

继续软件大赛的题目,苦恼的是解题过程中并没有融入Java的思想。

        题目:625这个数字很特别,625的平方等于390625,刚好其末3位是625本身。除了625,还有其它的3位数有这个特征吗?还有一个!该数是:_____________

        解题代码:

      

public class test3 {
public static void main(String[] args) {
  double b;
  int c;
  int a;
  for(int i = 100; i < 1000; i++) {
   a = i;
   b = a * a;
   c = (int)b % 1000;
   if(c == a && a != 625)
    System.out.println("a:" + a);
  }
  }

}

题目:

1、任意给出一个四位数, 把它重新组成一个四位的最大数和一个最小数, 算出两者间的差。

例如:3721这个数,可以重组成:7321和1237,相数之差为7321-1237

解题代码:

import java.io.*;

public class timu1 {
public static void main(String[] args) throws IOException{
  int big;
  int small;
  int b;
  InputStreamReader sReader = new InputStreamReader(System.in);
  BufferedReader bReader = new BufferedReader(sReader);
  System.out.println("请输入数字:");
  String shuzi = bReader.readLine();
  char[] s = new char[4];
  s[0] = shuzi.charAt(0);
  s[1] = shuzi.charAt(1);
  s[2] = shuzi.charAt(2);
  s[3] = shuzi.charAt(3);
  int[] a = new int[4];
  a[0] = s[0] - '0';
  a[1] = s[1] - '0';
  a[2] = s[2] - '0';
  a[3] = s[3] - '0';
 
  big = compare(a[0], a[1], a[2], a[3]);
  System.out.println("排列之后的较大数为:"
     + big);
  small = compare1(a[0], a[1], a[2], a[3]);
  System.out.println("排列之后的较小数为:" + small);
  b = big - small;
  System.out.println("较大数与较小数的差为:" + b);
}

private static int compare(int a, int b, int c, int d) {
  int test;
  int test1;
  int big;
  if(a < b) {
   test = a;
   a = b;
   b = test;
  }
  if(b < c) {
   if(a < c) {
    test = a;
    a = c;
    c = b;
    b = test;
   }
  }
  if(c < d) {
   if(a < d) {
    test = a;
    a = d;
    test1 = b;
    b = test;
    d = c;
    c = test1;
   }
   if(b < d) {
    test = b;
    b = d;
    d = c;
    c = test;
   }
   if(c < d) {
    test = c;
    c = d;
    d = test;
   }
  }
  big = a * 1000 + b * 100 + c * 10 + d;
  return big;
}

private static int compare1(int a, int b, int c, int d) {
  int test;
  int test1;
  int small;
  if(a > b) {
   test = a;
   a = b;
   b = test;
  }
  if(b > c) {
   if(a > c) {
    test = a;
    a = c;
    test1 = b;
    b = test;
    c = test1;
   }
   else {
    test = b;
    b = c;
    c = test;
   }
  }
  if(c > d) {
   if(a > d) {
    test = a;
    test1 = b;
    a = d;
    b = test;
    d = c;
    c = test1;
   
   }
   if(b > d) {
    test = b;
    test1 = c;
    b = d;
    c = test;
    d = test1;
   }
   if(c > d) {
    test = c;
    c = d;
    d = test;
   }
  }
  small = a * 1000 + b * 100 + c * 10 + d;
  return small;
}

}

利用Java类库中给出的方法就可实现排序,无需自己给出算法:


 

posted @ 2012-03-10 07:38  Java EE  阅读(304)  评论(0编辑  收藏  举报