题目
解:
(1)将数字转对应进制数
(2)检查是否满足幸运数字
完整代码
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static boolean transfer(int num,int code){
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
int x = num;
int i = 0;
while(x != 0){
a.add(x % code);//a列表存储进制转换的余数
x /= code;
}
int sum = 0;
for(int j=0; j < a.size(); j++){//进制余数求和
sum += a.get(j);
}
if( num % sum == 0 ) return true;
return false;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = 10;
int luck = 126;
ArrayList<Integer> list = new ArrayList<>();
while(true){
luck += 1;
if(transfer(luck,2) && transfer(luck,8) && transfer(luck,16) && transfer(luck,10)){//二、十、八、十六进制都满足才是幸运数字
list.add(luck);
n += 1;
}
if( n == 2023 ){
break;
}
}
for(int j = 0; j < list.size(); j++){
System.out.println(j+" "+list.get(j));
}
scan.close();
}
}
答案
215040
总结
1.进制转换
public static String transfer2(int num,int code){
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
String[] param = {"A","B","C","D","E","F"};//10 11 12 13 14 15
int x = num;
while(x != 0){
a.add(x % code);
x /= code;
}
for(int j = a.size()-1; j >= 0; j--){
b.add(a.get(j));
}
String res = "";
for(int j=0; j < b.size(); j++ ){
if( b.get(j) >= 10){
res += param[b.get(j)%10];
}else{
res += Integer.toString(b.get(j));
}
}
return res;
}
@Test
public void test1(){
int num = 126;
System.out.println(transfer2(num,2));
System.out.println(transfer2(num,10));
System.out.println(transfer2(num,8));
System.out.println(transfer2(num,16));
}
2.各位数拆分
public ArrayList<Integer> split(int num){
int x = num;
ArrayList<Integer> y = new ArrayList<Integer>();
while(x != 0){
y.add(x % 10);
x /= 10;
}
return y;
}
@Test
public void test2(){
ArrayList<Integer> list = split(1290);
System.out.println(list);
}