4/19/2007

无聊时做着玩的

今天在网上搜到一个据说是IBM的招聘题,看到一个问题有高人给出两个解法,于是就生了验证一下哪个正确的想法,就做了一下试验,结果编上瘾了,把其它两个也编了一把,发来瞅瞅吧,如果有高人愿意教点高级算法的应用就爽了
当然了,这些都很初级。。。

//在一个平面上画1999条直线最多能将这一平面划分成多少个部分?
package com.lyj.app;

public class Line {
int j1(int n) {
int i = 1 + n * (n - 1) / 2 + n;
return i;
}

int j2(int n1) {
int j = 1 + (1 + n1) * n1 / 2;
return j;
}

public static void main(String[] args) {
Line line = new Line();
System.out.println(line.j1(1999));
System.out.println(line.j2(1999));
}
}
//答案均为1999001

/* 27个小运动员在参加完比赛后,口渴难耐,去小店买饮料,饮料店搞促销,
* 凭三个空瓶可以再换一瓶,他们最少买多少瓶饮料才能保证一人一瓶?
*
* 这个问题,如果不是事先知道答案,可能就会有一个多出二瓶来的算法。要多注意编程细节
*/
package com.lyj.app;

public class Fenshui {
public static void main(String[] args) {
int ren, step, shui;
ren = 27;
step = 3;
shui = 1;
for (int i = 1; i <= ren; i++, shui++) {
if (i == 27)
break;
if (i % step == 0)
i += 1;
}
System.out.println(shui);
}
}


/* 一只蜗牛从井底爬到井口,每天白天蜗牛要睡觉,晚上才出来活动,一个晚上
* 蜗牛可以向上爬3尺,但是白天睡觉的时候会往下滑2尺,井深10尺,问蜗牛
* 几天可以爬出来?
*/
package com.lyj.app;

public class Woniu {
public static void main(String[] args) {
int max = 10, up = 3, down = 2, day, i = 0;
for (day = 1; day <= max; day++) {
i += up;
if (i == 10)
break;
i -= down;
}
System.out.println(day);
}
}

No comments: