一个数字的位数?

时间:2013-02-26 01:54:56

标签: java time-complexity

我编写了一个程序来查找java中给定数字的位数。这是一个很好的方法吗?该计划的时间复杂性是什么:

import java.util.*;

public class Inst {
     /**
     * @param args
     */
    public static void main(String[] args) {

            Scanner sc = new Scanner(System.in);
             double a = sc.nextDouble();
            for(int n=0;n<200000;n++)
            {
             double b=Math.pow(10, n);

             double d=a/b; 
            if(d>=0 & d<=9)
            {
                System.out.println("The number has "+(n+1)+" DIGITS");
                break;
            }
            }

    }

}

5 个答案:

答案 0 :(得分:1)

import java.util.*;

public class JavaLength {
  public static void main(String[] args){ 
   Scanner sc = new Scanner(System.in);
   Double d = sc.nextDouble();
   String dString = d.toString();
   System.out.println(d);
   if(dString.contains(".")){
      System.out.println("Total Characters: " + (dString.length() -1 ));
   }else{
      System.out.println("Total Characters: " + (dString.length()));
   } /*-1 for the '.' in between, if it exists!*/
}

答案 1 :(得分:1)

这个怎么样?

double input = Input;
int length = (input + "").length();

答案 2 :(得分:0)

FWIW,测试表示整数所需的(十进制)数字的最有效方法是if / else测试树。复杂性将是O(1),但代码将是UGLY(但可移植); e.g。

int num = ...

if (num >= 0)
    if (num < 1000000)
        if (num < 10000)
            if (num < 100)
                if (num < 10)
                    return 1
                else
                    return 2
            else 
                ...
        else
            ...
    else 
        ...
else 
    ...

答案 3 :(得分:0)

使用pow / log通常不是一个好的解决方案,因为可能有一个接近10的幂的数字转向下一个整数。在双精度中,应该能够精确地存储log10应该绝对的所有15位数字。 15.实际上,log10(10 ^ 15 - 100)仍然是15。

将会遇到相同的算法,这些算法在十进制到字符串转换中内部使用:

试验部门

while (i > 0) { i=i/10;  count++; }

试用乘法

j=10; while (i >= j) { j*=10; count++; }

试验从msb到lsb 转换为字符串;

j=10000000; while (i>0) { 
                 while (i>=j) { digit++;i-=j;}; 
                 j/=10; *str++=digit+'0'; digit=0:
            }

使用double dabble algorithm进行二进制到bcd转换,其中每个数字由缩小的十六进制数字表示(省略a-f)。

答案 4 :(得分:0)

此逻辑最初是用c ++编写的,但是我认为这是查找数字位数,以相反顺序存储它们并查找数字总和的最佳方法。

int n;
int count=0, sum=0;
int j=0;
int ar[10];    //array to store digits

cin>> n;      //input number
do{
    if((n/10)==0){
        count++;
        ar[j]=n;
        break;
    }
    
    else{
        count++;
        ar[j]= (n%10);
        j++;
        n=int(n/10);
    }
}

`
while((n/10)!=0||(n%10)!=0);

cout<<"The number of digits is: "<<count<<"\n"<<"The reverse number is: ";

for(int u=0;u<count;u++){
    cout<<ar[u];
    sum+=ar[u];
}
cout<<"\n"<< "Sum of digits is: "<< sum;
}`
相关问题