06 Apr 2019
【Algorithm】 003 算法基础
编码
时间限制:1秒
空间限制:32768K
假定一种编码的编码范围是a ~ y的25个字母,从1位到4位的编码,如果我们把该编码按字典序排序,形成一个数组如下: a, aa, aaa, aaaa, aaab, aaac, … …, b, ba, baa, baaa, baab, baac … …, yyyw, yyyx, yyyy 其中a的Index为0,aa的Index为1,aaa的Index为2,以此类推。 编写一个函数,输入是任意一个编码,输出这个编码对应的Index.
输入描述: >输入一个待编码的字符串,字符串长度小于等于100.
输出描述: >输出这个编码的index
输入例子1: >baca
输出例子1: >16331
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.nextLine();
char[] s = str.toCharArray();
int ans = 0;
for (int i = 0; i < str.length(); i++) {
int m = 0;
int j = 3 - i;
while (j >= 0) {
m += Math.pow(25, j);
j--;
}
ans = ans + (s[i] - 'a') * m + 1;
}
System.out.println(ans - 1);
}
}
}
游戏任务标记
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] task = new int[1025];
while (sc.hasNext()) {
int id1 = sc.nextInt();
int id2 = sc.nextInt();
if (id1 > 1024 || id1 < 1 || id2 > 1024 || id2 < 1) {
System.out.println(-1);
continue;
}
task[id1] = 1;
System.out.println(task[id2]);
}
}
}
素数对
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean[] isPrime = new boolean[1000];
for (int i = 0; i < 1000; i++) {
isPrime[i] = true;
}
isPrime[0] = isPrime[1] = false;
for (int i = 2; i < 32; i++) {
if (isPrime[i]) {
int j = i + i;
while (j < 1000) {
isPrime[j] = false;
j = j + i;
}
}
}
while (sc.hasNext()) {
int n = sc.nextInt();
int count = 0;
for (int i = 0; i < n / 2; i++) {
if (n % 2 == 0) {
if (isPrime[n / 2 + i] && isPrime[n / 2 - i]) {
count++;
}
} else {
if (isPrime[n / 2 - i] && isPrime[n / 2 + i + 1]) {
count++;
}
}
}
System.out.println(count);
}
}
}
geohash编码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int lb = -90;
int ub = 90;
String str = "";
for (int i = 0; i < 6; i++) {
int mid = (ub + lb) / 2;
if (n >= mid) {
lb = mid;
str += "1";
} else {
ub = mid;
str += "0";
}
}
System.out.println(str);
}
}
}
Til next time,
gentlesnow
at 21:22
