Saturday, December 17, 2016

Get digit of an integer (int type) Java

  public int getDigit(int x){
    int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE };
    
    if(x < 0) x = Math.abs(x);
    
    for(int i = 0; ;i++){
      if(x < sizeTable[i])
        return i+1;
    }
  }