分类 笔记 下的文章

快速判断整数多少位


Java Integer包中的实现源代码:

    public class Test {    
    final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,    
            99999999, 999999999, Integer.MAX_VALUE };    
    static int sizeOfInt(int x) {    
        for (int i = 0;; i++)    
            if (x <= sizeTable[i])    
                return i + 1;    
    }    
    public static void main(String[] args) {    
        System.out.println(sizeOfInt(1234));    
        System.out.println(sizeOfInt(123));    
        System.out.println(sizeOfInt(12345));    
        System.out.println(sizeOfInt(12));    
    }
}    

另一种转为字符串方法:

  public class java_run {

  public static void main(String[] args) 
  {
      System.out.print(length(287785));
  }
    
  public static int length(int number)
  {
      int length = (number + " ").length();
      return length;
  }
}

其余方法还有除法等……嗯