因此,您似乎从 8 个答案中得到了解决方案。:)
我只想对此进行测试,看看哪个更快(我的)或 3 循环方法。
这是代码(您不必以任何方式理解它),除了一种方法 - printSquare(int number)是唯一与您相关的方法。其余的与卡尺框架有关——我用它来测量一些结果。
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
public class Measure extends SimpleBenchmark {
public static void main(String[] args) {
Runner.main(Measure.class, args);
}
@Param({"1"})
private int mins;
@Param({"4","7","9"})
private int maxs;
public void timePrintSquare3Loops(int reps){
for(int i=0;i<reps;++i){
printSquareTwo(mins, maxs);
}
}
public void timePrintSquareMine(int reps){
for(int i=0;i<reps;++i){
printSquareOne(mins, maxs);
}
}
public void timePrintSquareTwoLoops(int reps){
for(int i=0;i<reps;++i){
printSquareTwoLoops(mins, maxs);
}
}
/**
* the general solution with 3 loops
*/
public void printSquareTwo(int min,int max){
for(int i=min;i<=max;i++){
for(int j=i;j<=max;j++) System.out.print(j);
for(int k=min;k<i;k++) System.out.print(k);
}
}
public static void printSquareTwoLoops(int min, int max) {
int x = max - min + 1;
for (int i = min; i <= max; i++) {
int counter = i;
for (int j = 0; j < x; j++) {
System.out.print(counter);
counter = counter >= max ? min : counter + 1;
}
System.out.println();
}
}
/**
* If you know the number upfront. for example 345678.
* 345678-3*10000=45678=>most significatDigit=3, difference = 45678.
* number = 45678*10 + significatDigit=456783
*
* And so on..
*
*/
public void printSquareOne(int min, int max){
StringBuilder sb = new StringBuilder();
for(int i=min;i<=max;++i){sb.append(i);}
int number = Integer.valueOf(sb.toString());
int howMany = (""+number).length();
for(int i=0;i<howMany;++i){
int pow = (int)Math.pow(10, (howMany-1));
int mostSignificantDigit = 0;
int intermediarResult = number;
do {
++mostSignificantDigit;
intermediarResult = intermediarResult - pow;
} while (intermediarResult>pow);
number = intermediarResult * 10 + mostSignificantDigit;
System.out.println(number);
}
}
}
我进行了一些测试。
编辑我还在测试中添加了@Arun P Johny 方法。
这是输出:
4 PrintSquare3Loops 32.4 =====
4 PrintSquareMine 20.7 ===
4 PrintSquareTwoLoops 38.4 ======
4 PrintSquareCollections 31.8 =====
7 PrintSquare3Loops 92.9 ==============
7 PrintSquareMine 36.8 =====
7 PrintSquareTwoLoops 102.6 ================
7 PrintSquareCollections 104.8 ================
9 PrintSquare3Loops 166.2 ==========================
9 PrintSquareMine 41.7 ======
9 PrintSquareTwoLoops 187.5 ==============================
9 PrintSquareCollections 147.7 =======================
似乎一个接一个的3个循环对性能没有那么好。我在这里谈论内存,我相信我的会使用更多。