火星计数法
Time Limit: 1000 ms
Memory Limit: 65536 KiB
Problem Description
火星人的计数规则里只有a,b,c,d四个字母,计数规则从小到大是 a,b,c,d,aa,ab,ac,ad,ba,……。
给出来由a,b,c,d四种字母组成的火星数字,算出该数字是第几个(从1开始)。
Input
第一行输入一个数T代表测试用例组数(T<=200),接下来T组测试用例,每组测试数据为一个火星数字(长度小于100)。
Output
对于每组测试用例,输出该火星数字代表多少(结果对10000007取模)。每行输出一个结果。
Sample Input
2 a ab
Sample Output
1 6
Hint
快速幂
参考:https://blog.youkuaiyun.com/qq_16255321/article/details/41983919
https://blog.youkuaiyun.com/alps1992/article/details/42131581
Source
中国海洋大学第三届“朗讯杯”编程比赛高级组试题
//package leslie;//本题可以看做是求五进制串表示的值
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n=cin.nextInt();
String getchar=cin.nextLine();
while(n-->0)
{
char arr[]=cin.nextLine().toCharArray();
long sum=0;
for(int i=0;i<arr.length-1;i++)
sum=(sum+arr[i]-'a'+1)*4;
sum=sum+arr[arr.length-1]-'a'+1;//加上字符串最后一位表示的值
sum%=10000007;
System.out.println(sum);
}
cin.close();
}
}
//package leslie;//本题因为数值较大,可以用快速幂求解
import java.util.*;
public class Main {
static char arr[] = new char[105];
final static int Mod = 10000007;
public static long Fast_Power(long p, long n) { // 快速幂
long ans = 1, base = p;
while (n != 0) {
if (n % 2 == 1)
ans *= base % Mod;
base *= base % Mod;
n = n / 2;
}
return ans;
}
public static void Ans() {
long sum = 0;
for (int i = 0; i < arr.length; i++) {
long n = arr[i] - 'a' + 1;
sum = (sum + (n * Fast_Power(4, arr.length - i - 1))) % Mod;// 可以把字符串每一位看成一层,一层一层叠加求出答案
}
System.out.println(sum);
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
String getchar = cin.nextLine();
while (n-- > 0) {
arr = cin.nextLine().toCharArray();
Ans();
}
cin.close();
}
}
/*
* 快速幂另一种写法 if(n==0)return 1; long ans=Fast_Power(p,n/2); ans=ans*ans%Mod;
* if(n&1)ans=ans*p%Mod; return ans;//n&1即n%2==1
*/