Return first digit of an integer

后端 未结 23 1571
醉梦人生
醉梦人生 2020-11-28 13:12

How in Java do you return the first digit of an integer.?

i.e.

345

Returns an int of 3.

相关标签:
23条回答
  • 2020-11-28 14:09
    public static int firstDigit(int n) {
      while (n < -9 || 9 < n) n /= 10;
      return Math.abs(n);
    }
    

    Should handle negative numbers pretty well, too. Will return a negative first digit in that case.

    0 讨论(0)
  • 2020-11-28 14:09
    public static void firstDigit(int number){      
        while(number != 0){
            if (number < 10){
                System.out.println("The first digit is " + number);
            }
                number = number/10;
    
            }
        }
    

    When you call it, you can use Maths.abs in order for it to work for negative number:

    firstDigit(Math.abs(9584578)); 
    

    This returns 9

    0 讨论(0)
  • 2020-11-28 14:10

    Yet another way:

    public int firstDigit(int x) {
      if (x == 0) return 0;
      x = Math.abs(x);
      return (int) Math.floor(x / Math.pow(10, Math.floor(Math.log10(x))));
    }
    
    0 讨论(0)
  • 2020-11-28 14:10

    I find this one more simpler:

    int firstDigit(int num)
    {
        if(num/10 == 0)
            return num;
        return firstDigit(num/10);
    
    }
    
    • Input: 123 => Output: 1
    • Input: -123 => Output: -1
    0 讨论(0)
  • 2020-11-28 14:10
    int firstNumber(int x){
         int firstN = x;
         while(firstN > 9){
              firstN = (firstN - (firstN%10))/10;
         }
         return firstN;   
     }
    
    0 讨论(0)
提交回复
热议问题