// Requires positive x staticintstringSize2(int x){ int p = 10; for (int i=1; i<11; i++) { if (x < p) return i; p = 10*p; } return10; }
好吧,目前我就想到了除JDK以外的这三种方法。
我们测试一下我们的代码正确性。
1 2 3 4 5 6 7 8 9 10
publicstaticvoidmain(String[] args){ int [] x=newint[]{5,10,333,6666,77777,123456,1234567,87654321,999999999,1111111111,Integer.MAX_VALUE}; for(int i=0;i<x.length;i++){ int a1=Test.stringSize1(x[i]); int a2=Test.stringSize2(x[i]); int a3=Test.myStringSize1(x[i]); int a4=Test.myStringSize2(x[i]); System.out.println(a1+"---"+a2+"---"+a3+"---"+a4); } }
long start1=System.nanoTime(); for(int i=0;i<xArrays.length;i++) { stringSize1(xArrays[i]); } long end1=System.nanoTime(); long time1=(end1-start1)/1000; System.out.println("JDK方法耗时---》"+time1+"ms"); cellList.add(time1);
long start4=System.nanoTime(); for(int i=0;i<xArrays.length;i++) { stringSize2(xArrays[i]); } long end4=System.nanoTime(); long time4=(end4-start4)/1000; System.out.println("乘法耗时---》"+time4+"ms"); cellList.add(time4);
long start2=System.nanoTime(); for(int i=0;i<xArrays.length;i++) { myStringSize1(xArrays[i]); } long end2=System.nanoTime(); long time2=(end2-start2)/1000; System.out.println("String方法耗时---》"+time2+"ms"); cellList.add(time2);
long start3=System.nanoTime(); for(int i=0;i<xArrays.length;i++) { myStringSize2(xArrays[i]); } long end3=System.nanoTime(); long time3=(end3-start3)/1000; System.out.println("除法耗时---》"+time3+"ms"); cellList.add(time3);