汉诺塔问题&数组Dominato&non-negative integer

[b]1 汉诺塔运行结果:[/b]
[quote]input number: 5
Disk 1 From A To C
Disk 2 From A TO B
Disk 1 From C To B
Disk 3 From A TO C
Disk 1 From B To A
Disk 2 From B TO C
Disk 1 From A To C
Disk 4 From A TO B
Disk 1 From C To B
Disk 2 From C TO A
Disk 1 From B To A
Disk 3 From C TO B
Disk 1 From A To C
Disk 2 From A TO B
Disk 1 From C To B
Disk 5 From A TO C
Disk 1 From B To A
Disk 2 From B TO C
Disk 1 From A To C
Disk 3 From B TO A
Disk 1 From C To B
Disk 2 From C TO A
Disk 1 From B To A
Disk 4 From B TO C
Disk 1 From A To C
Disk 2 From A TO B
Disk 1 From C To B
Disk 3 From A TO C
Disk 1 From B To A
Disk 2 From B TO C
Disk 1 From A To C
[/quote]


import java.io.*;

public class Hanoi {
public static void main(String args[]) throws IOException {
int n;
BufferedReader buf;
buf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("input number: ");
n = Integer.parseInt(buf.readLine());
Hanoi hanoi = new Hanoi();
hanoi.move(n, 'A', 'B', 'C');
}

public void move(int n, char a, char b, char c) {
if (n == 1)
System.out.println("Disk " + n + " From " + a + " To " + c);
else {
move(n - 1, a, c, b);
System.out.println("Disk " + n + " From " + a + " TO " + c);
move(n - 1, b, a, c);
}
}
}



[b]2 Array Dominator [/b]
import java.util.Hashtable;

import junit.framework.TestCase;

public class Dominator extends TestCase {
public static int dominator(int[] a) {
int result = -1;
int length = a.length;

Hashtable<Integer, Integer> countTable = new Hashtable<Integer, Integer>();

for (int i = 0; i < length; i++) {
if (countTable.containsKey(a[i])) {
countTable.put(a[i], countTable.get(a[i]) + 1);
if (countTable.get(a[i]) >= length / 2) {
return i;
}
} else {
countTable.put(a[i], 0);
}
}
return result;
}

public void testDominator() {
int[] array = { 1, 2, 3, 3, 3, 3, 3 };
assertEquals(dominator(array), 5);
}

}





public class HeavyNumberTest {
static int count = 0;

public static void main(String a[]) {
// should be 5
System.out.println(heavy(8675, 8689));
}

static int heavy(int a, int b) {
int range = 0;

if (a == 0 || b == 0)
return 0;

if (a > b)
range = a - b;
else
range = b - a;

for (int j = 0; j <= range; j++) {
double avg = 0.0;
int sum = 0;
int n = 0;

int currentNumber = a;
while (currentNumber > 0) {
sum += currentNumber % 10;
currentNumber = currentNumber / 10;
n++;
}

avg = ((double) sum) / ((double) n);
if (avg > 7)
count++;

System.out.println(" " + avg + " \t " + count);

a++;
}

return count;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值