时间限制:C/C++语言 1000MS;其他语言 3000MS
内存限制:C/C++语言 65536KB;其他语言 589824KB题目描述:
小明同学学习了不同的进制之后,拿起了一些数字做起了游戏。小明同学知道,在日常生活中我们最常用的是十进制数,而在计算机中,二进制数也很常用。现在对于一个数字x,小明同学定义出了两个函数f(x)和g(x)。
f(x)表示把x这个数用十进制写出后各个数位上的数字之和。如f(123)=1+2+3=6。
g(x)表示把x这个数用二进制写出后各个数位上的数字之和。如123的二进制表示为1111011,那么g(123)=1+1+1+1+0+1+1=6。
小明同学发现对于一些正整数x满足f(x)=g(x),他把这种数字称为幸运数,现在他想知道,小于等于n的幸运数有多少个。
第一行一个整数T(T<=10000)表示数据组数,每组数据输入一个数n(n<=100000)。
输出
每组数据输出一行,小于等于n的幸运数个数。
样例输入
31
5
21
样例输出
1
1
3
Hint
小于等于21的三个幸运数分别为:1,20,21
代码如下:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int c = sc.nextInt();
int out[] = new int[c];
int in[] = new int[c];
for (int i = 0; i < in.length; i++) {
in[i] = sc.nextInt();
}
Main.solution(in, out);
}
}
public static void solution(int[] str, int[] res) {
int sRes = 0;
int eRes = 0;
int count = 0;
for (int i = 0; i < str.length; i++) {
count = 0;
for (int j = 1; j <= str[i]; j++) {
sRes = sumDig(j);
eRes = sumBin(j);
if (sRes == eRes) {
count++;
}
}
res[i] = count;
}
for (int j = 0; j < res.length; j++) {
System.out.println(res[j]);
}
}
public static int sumBin(int num) {
String str = Integer.toBinaryString(num);
int count = 0;
char t = '1';
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == t) {
count = count + 1;
}
}
return count;
}
public static int sumDig(int n) {
int result = 0;
while (n != 0) {
result += n % 10;
n /= 10;
}
return result;
}
}