Java代码
packagecom.zhonghaiwangluokeji.interview;
/**
* 0-9这十个数,组合成两个三位数和一个四位数
* 求出满足条件:两个三位数相加等于那个四位数
* 的所有这些数
* @author yangjianzhou
*
*/
publicclassProblem3 {
publicstaticvoidmain(String[] args) {
printNumbers();
}
publicstaticvoidprintNumbers(){
intresult =0;
for(inti=123;i<=987;i++){
for(intj=123;j<=987;j++){
result = i+j;
if((result>1000)&&isTrue(result,i,j)){
System.out.print(result+" ");
System.out.print(i+" ");
System.out.println(j+" ");
}
}
}
}
publicstaticbooleanisTrue(intresult,inti,intj){
String str ="0123456789";
String s = result+""+i+""+j;
intindex =0;
String str1 ="";
for(intk =0;k
index = s.indexOf(str.charAt(k));
if(index>=0){
str1 = s.replaceFirst(str.charAt(k)+"","a");
s = str1;
}
}
String s1 = s.replaceAll("a","");
if(s1.length()==0){
returntrue;
}
returnfalse;
}
}
package com.zhonghaiwangluokeji.interview;
/**
* 0-9这十个数,组合成两个三位数和一个四位数
* 求出满足条件:两个三位数相加等于那个四位数
* 的所有这些数
* @author yangjianzhou
*
*/
public class Problem3 {
public static void main(String[] args) {
printNumbers();
}
public static void printNumbers(){
int result = 0;
for(int i=123;i<=987;i++){
for(int j=123;j<=987;j++){
result = i+j;
if((result>1000)&&isTrue(result,i,j)){
System.out.print(result+" ");
System.out.print(i+" ");
System.out.println(j+" ");
}
}
}
}
public static boolean isTrue(int result,int i,int j){
String str = "0123456789";
String s = result+""+i+""+j;
int index = 0;
String str1 = "";
for(int k =0;k
index = s.indexOf(str.charAt(k));
if(index>=0){
str1 = s.replaceFirst(str.charAt(k)+"", "a");
s = str1;
}
}
String s1 = s.replaceAll("a", "");
if(s1.length()==0){
return true;
}
return false;
}
}
运行结果:
Java代码
1035246789
1035249786
1053264789
1053269784
1053284769
1035286749
1035289746
1053289764
1089324765
1089325764
1098342756
1098346752
1206347859
1206349857
1098352746
1098356742
1206357849
1206359847
1089364725
1089365724
1098423675
1098425673
1305426879
1305429876
1089432657
1026437589
1089437652
1026439587
1089452637
1089457632
1062473589
1098473625
1098475623
1305476829
1062479583
1305479826
1062483579
1026487539
1026489537
1062489573
1026537489
1026539487
1062573489
1062579483
1062583479
1026587439
1026589437
1062589473
1098623475
1503624879
1098625473
1503629874
1089632457
1089637452
1089652437
1089657432
1098673425
1503674829
1098675423
1503679824
1089724365
1089725364
1098742356
1602743859
1035746289
1098746352
1035749286
1602749853
1098752346
1602753849
1098756342
1602759843
1053764289
1089764325
1089765324
1053769284
1053784269
1035786249
1035789246
1053789264
1503824679
1305826479
1305829476
1503829674
1602843759
1206847359
1206849357
1602849753
1602853749
1206857349
1206859347
1602859743
1503874629
1305876429
1305879426
1503879624