幸运数


时间限制: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的幸运数个数。

样例输入

3
1
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;
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值