繁体   English   中英

一个数字的位数?

[英]Number of digits in a number?

我写了一个程序来找出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;
            }
            }

    }

}
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!*/
}

这个怎么样?

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

FWIW,测试表示整数所需的(十进制)位数的最有效方法将是 if / else 测试树。 复杂度将是O(1) ,但代码将是丑陋的(但可移植); 例如

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 
    ...

使用 pow / log 通常不是一个好的解决方案,因为可能有一个接近 10 的幂的数字四舍五入到下一个整数。 在双精度中,应该能够精确存储所有 15 位数字,其中 log10 应该绝对 < 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 算法的二进制到 bcd 转换,其中每个数字由一组减少的十六进制数字表示(省略 af)。

这个逻辑最初是用 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;
}`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM