Java学习心得之各种小算法

 

1、计算两个日期差多少天的方法,代码如下

 1 /**
 2 * 这个方法可以比较两个日期的相差天数。先输入小的日期
 3 */
 4 private static void DateCha() {
 5     Scanner datein = new Scanner(System.in);
 6     Scanner input1 = new Scanner(datein.nextLine()).useDelimiter("-");
 7     Scanner input2 = new Scanner(datein.nextLine()).useDelimiter("-");
 8     Calendar cal1 = Calendar.getInstance(), cal2 = Calendar.getInstance();
 9 
10     cal1.set(input1.nextInt(), input1.nextInt(), input1.nextInt());
11     cal2.set(input2.nextInt(), input2.nextInt(), input2.nextInt());
12 
13     for (int i = 0; ; i++) {
14         cal1.add(Calendar.DATE, i);
15         if (cal1.equals(cal2))
16             System.out.println("差天数" + i);
17         else
18             cal1.add(Calendar.DATE, -i);
19         }
20     datein.close();
21     input1.close();
22     input2.close();
23 }

输入的是1990-07-282013-09-13

 

2、求两个整数的最大公约数的算法,如下

1 static int gcd(int M, int N) {
2     if (N == 0)
3         return M;
4     return gcd(N, M % N);
5 }

 3、约瑟夫问题的Java求解,代码如下,其中对于指针的应用非常好,代码值得推敲

 

 1 /**
 2  * 约瑟夫问题,指针的用法
 3  */
 4 public class Josephus {
 5     static class Node{
 6         int val;    Node next;
 7         Node(int v){
 8             val=v;
 9         }
10     }
11     public static void main(String[] args) {
12         Scanner sc=new Scanner(System.in);
13         int M=sc.nextInt();        //总共有多少人
14         int N=sc.nextInt();        //第几个人出去
15         Node t=new Node(1);        //首节点
16         Node x=t;                //定义一个指针,这个指针也是指向t的,是为了增加节点而设置的
17         for(int i=2;i<=N;i++)
18             x=(x.next=new Node(i));        //其中第一次循环x.next就是t的下一个节点,创建一个新的结点
19                                         //然后把x指针下移
20         x.next=t;                        //把尾指针赋值给头指针
21         while(x!=x.next){
22             for(int i=1;i<M;i++)
23                 x=x.next;
24             x.next=x.next.next;
25         }
26         System.out.println("survivor is "+x.val);
27     }
28 
29 }

 

posted @ 2012-09-07 22:33  Lowp  阅读(328)  评论(0编辑  收藏  举报