恢复恢复~
250
public class DivisorDigits {
public int howMany(int number) {
int result = 0;
int temp = number;
while (temp > 0) {
if ((temp % 10) != 0) {
if (number % (temp % 10) == 0) {
result++;
}
}
temp /= 10;
}
return result;
}
}
简单的一道题
600
译码的问题,因为char是8位的可以直接用256的数组来取代map,两个map,一个是代表键盘值到实际值的映射,另一个就是实际值到键盘显示值的映射
public class CeyKaps {
public String decipher(String typed, String[] switches) {
char[] map = new char[256];
char[] rav = new char[256];
for (char c='A';c<='Z';c++) {
map[c] = c;
rav[c] = c;
}
for (String s : switches) {
char a = s.charAt(0);
char b = s.charAt(2);
char temp = map[a];
map[a] = map[b];
map[b] = temp;
rav[map[a]] = a;
rav[map[b]] = b;
}
String result = "";
for (char c : typed.toCharArray()) {
result += rav[c];
}
return result;
}
}
1000
就是列出来所有可能的数字组合,之后判断是否可行。主要的难点在于全排列,这里用了字典序的全排列。应该把这个背下来。。这也是C++的STL库用的算法。排序也是为了先生成最小的字典序。每次调用nextPermutation都是下一个字典序,直达最大的字典序。具体的算法介绍参见
http://www.cnblogs.com/pmars/archive/2013/12/04/3458289.html
import java.util.Arrays;
public class MNS {
public int combos(int[] numbers) {
Arrays.sort(numbers);
int count = 0;
do {
if (check(numbers)) {
count++;
}
} while (XArrays.nextPermutation(numbers, numbers.length));
return count;
}
private boolean check(int[] numbers) {
final int N = 3;
final int sum = XArrays.sum(numbers, 0, 3);
for (int i = 0; i < N; i++) {
int s1 = 0;
int s2 = 0;
for (int j = 0; j < N; j++) {
s1 += numbers[i * N + j];
s2 += numbers[j * N + i];
}
if (s1 != sum || s2 != sum) {
return false;
}
}
return true;
}
}
class XArrays {
public static boolean nextPermutation(int[] array, int n) {
for (int i = n - 2; i >= 0; i--) {
if (array[i] < array[i + 1]) {
for (int j = n - 1; ; j--) {
if (array[i] < array[j]) {
swap(array, i, j);
for (i++, j = n - 1; i < j; i++, j--) {
swap(array, i, j);
}
return true;
}
}
}
}
return false;
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static int sum(int[] array, int from, int to) {
int total = 0;
for (int i = from; i < to; i++) {
total += array[i];
}
return total;
}
}