Return first digit of an integer

后端 未结 23 1573
醉梦人生
醉梦人生 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:00

    This is Groovy, but it should be easy to convert to Java:

    int firstNum(int x) {
        a = Math.abs(x)
        sig = Math.floor(Math.log10(a))
        return a / Math.pow(10, sig)
    }
    

    Results:

    groovy> println(firstNum(345))
    3

    groovy> println(firstNum(3452))
    3

    groovy> println(firstNum(-112))
    1

    groovy> println(firstNum(9999))
    9

    groovy> println(firstNum(Integer.MAX_VALUE))
    2

    groovy> println(firstNum(Integer.MIN_VALUE + 1))
    2

    0 讨论(0)
  • 2020-11-28 14:01
    //Try this one.
    Scanner input = new Scanner(System.in);
    System.out.println("enter first 9 digits: ");
    String x = input.nextLine();
    String x1 = x.substring(0,1);
    int d1 = Integer.parseInt(x1);
    System.out.println(d1);
    // the substring gives the position of extraction. method dont seem to work for letters though
    
    0 讨论(0)
  • 2020-11-28 14:02

    Looking at the code supplied it seems a tad over complicating the whole thing, here is a simple solution...

    int number = 4085;
    int firstDigit = number;
    while (firstDigit > 9)
    {
          firstDigit = firstDigit / 10;
    }
    System.out.println("The First Digit is " + firstDigit);
    
    0 讨论(0)
  • 2020-11-28 14:04

    Homework Hint: Convert it to a string and and return the first character.

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

    Here is a smaller version to get digits of all positions, it works with negative value (not decimal).

    int number = -23456;
    
    int length = (int) Math.log10(Math.abs(number)) + 1; //This gets the length of the number of digits used
    //Math.abs to change negative int to positive
    
    System.out.println("Digit at pos " + 1 + " is :- " + (int)(Math.abs(number)/Math.pow(10,(length-1))));
    
    for (int i = 2; i <= length; i++){
        System.out.println("Digit at pos " + i + " is :- " + (int)(Math.abs(number)/Math.pow(10,(length-i))%10));
    }
    
    0 讨论(0)
  • 2020-11-28 14:04

    I think more simple to do :

    int firstDigit = i-(i/10)*10 // i is an integer or long value, positive or negative.
    
    0 讨论(0)
提交回复
热议问题