import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
/*解题思路:将4 和 7 抽象成 0 和 1,然后遍历0 到 n之间的数字,
* 将其转为二进制数,然后分别对其进行替换,将0 替换为4 将1 替换为7 ,
* 然后判断替换后的数字是否在 [0,n]区间之内,满足,则放入set中,
* 否则,跳过本次循环。最后返回set.size()*/
public class LuckNum {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
Set set = new TreeSet();
for (int i = 0; i <= n; i++) {
String a1 = toFullBinaryString(i, n);
a1 = a1.replace("0", "4").replace("1", "7");
int numa = Integer.parseInt(a1);
if (a1.length() > String.valueOf(Integer.MAX_VALUE).length()) {
if (a1.charAt(0) > 2)
break;
} else {
if (numa < n) {
set.add(numa);
}
}
String a2 = Integer.toBinaryString(i);
a2 = a2.replace("0", "4").replace("1", "7");
if (a2.length() >= String.valueOf(Integer.MAX_VALUE).length()) {
if (a2.charAt(0) > 2)
break;
} else {
int numa2 = Integer.parseInt(a2);
if (numa2 < n) {
set.add(numa2);
}
}
}
System.out.println(set);
System.out.println(set.size());
}
private static String toFullBinaryString(int x, int b) {
int size = String.valueOf(b).length();
if (size > 1) {
size -= 1;
}
int[] buffer = new int[size];
for (int i = (size - 1); i >= 0; i--) {
buffer[i] = x >> i & 1;
}
String s = "";
for (int j = (size - 1); j >= 0; j--) {
s = s + buffer[j];
}
return s;
}
}
输入:125,输出正确
输入:21857711,输出为:
[4, 7, 74, 77, 744, 747, 774, 777, 7444, 7447, 7474, 7477, 7744, 7747, 7774, 7777, 74444, 74447, 74474, 74477, 74744, 74747, 74774, 74777, 77444, 77447, 77474, 77477, 77744, 77747, 77774, 77777, 744444, 744447, 744474, 744477, 744744, 744747, 744774, 744777, 747444, 747447, 747474, 747477, 747744, 747747, 747774, 747777, 774444, 774447, 774474, 774477, 774744, 774747, 774774, 774777, 777444, 777447, 777474, 777477, 777744, 777747, 777774, 777777, 4444444, 4444447, 4444474, 4444477, 4444744, 4444747, 4444774, 4444777, 4447444, 4447447, 4447474, 4447477, 4447744, 4447747, 4447774, 4447777, 4474444, 4474447, 4474474, 4474477, 4474744, 4474747, 4474774, 4474777, 4477444, 4477447, 4477474, 4477477, 4477744, 4477747, 4477774, 4477777, 4744444, 4744447, 4744474, 4744477, 4744744, 4744747, 4744774, 4744777, 4747444, 4747447, 4747474, 4747477, 4747744, 4747747, 4747774, 4747777, 4774444, 4774447, 4774474, 4774477, 4774744, 4774747, 4774774, 4774777, 4777444, 4777447, 4777474, 4777477, 4777744, 4777747, 4777774, 4777777, 7444444, 7444447, 7444474, 7444477, 7444744, 7444747, 7444774, 7444777, 7447444, 7447447, 7447474, 7447477, 7447744, 7447747, 7447774, 7447777, 7474444, 7474447, 7474474, 7474477, 7474744, 7474747, 7474774, 7474777, 7477444, 7477447, 7477474, 7477477, 7477744, 7477747, 7477774, 7477777, 7744444, 7744447, 7744474, 7744477, 7744744, 7744747, 7744774, 7744777, 7747444, 7747447, 7747474, 7747477, 7747744, 7747747, 7747774, 7747777, 7774444, 7774447, 7774474, 7774477, 7774744, 7774747, 7774774, 7774777, 7777444, 7777447, 7777474, 7777477, 7777744, 7777747, 7777774, 7777777]
192
应该为254