Return first digit of an integer

后端 未结 23 1572
醉梦人生
醉梦人生 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 13:53

    I think this might be a nice way to do that:

    public static int length(int number) {
        return (int)Math.log10(Math.abs(number)) + 1;
    }
    
    public static int digit(int number, int digit) {
        for (int i = 0; i < digit; i++) {
            number /= 10;
        }
        return Math.abs(number % 10);
    }
    

    Works for both negative and positive numbers. digit(345, length(345) - 1) will return 3, digit(345, 0) will return 5 e.g. and so on...

    0 讨论(0)
  • 2020-11-28 13:54

    Assume the number is int type

    therefore,

    int number = 352
    // Change the int into String format
    String numberString = Integer.toString(number);
    // We can know the first digit of that String with substring method directly
    Integer.parseInt(numberString.substring(0,1));
    

    or the other way is to change the String into char and get the numerical value from char

    e.g.

    int number = 352;
    String numberString = Integer.toString(number);
    Character.getNumericValue(String.valueOf(target).charAt(0)); 
    // 0 means the first digit of the number
    
    0 讨论(0)
  • 2020-11-28 13:54

    Here's an extremely simple way of obtaining the first and second digits of an integer separately, but this will only work for exactly two digits!

        int firstDigit = number / 10;
        int secondDigit = number % 10;
    

    For a situation where the user might input more or less digits, but where you may not know how many, you could try this approach, but other answers have better solutions for this case. I just wrote this complete program up that you can paste into a compiler and run. Once you see the pattern you can check for as many digits as you want and then just have a catch for a length greater than you want to accept:

    package testingdigits;
    
    import java.util.Scanner;
    
    public class TestingDigits {
    
    
    Scanner keyboard = new Scanner(System.in);    
    
    public static void main(String[] args) 
    {
    
    Scanner keyboard = new Scanner(System.in);
    
    System.out.printf("\nEnter a number to test:");
    int number = keyboard.nextInt();
    
    int length = (int) Math.log10(number) + 1; //This gets the length of the number of digits used 
    
    //Initializing variables first to prevent error
    int firstDigit = 0, secondDigit = 0, thirdDigit = 0, fourthDigit = 0, fifthDigit = 0, sixthDigit = 0;
    
        if (length == 1)
         {
            firstDigit = number;
            System.out.println("" + firstDigit);
         }
        if (length == 2)
         {
            firstDigit = number / 10; //For example, 89/10 will output 8.9 and show as 8 in this case.
            secondDigit = number % 10;
            System.out.println("" + firstDigit + "" + secondDigit);
         }
        if (length == 3)
         {
            firstDigit = number / 10 / 10; // 123/10/10 is 1.23 and will show as 1
            secondDigit = number / 10 % 10;
            thirdDigit = number % 10;
            System.out.println("" + firstDigit + "" + secondDigit + "" + thirdDigit);
         }
        if (length == 4)
         {
            firstDigit = number / 10 / 10 / 10; 
            secondDigit = number / 10 / 10 % 10;
            thirdDigit = number / 10 % 10;
            fourthDigit = number % 10;
            System.out.println("" + firstDigit + "" + secondDigit + "" + thirdDigit + "" + fourthDigit);
         }
         if (length == 5)
         {
            firstDigit = number / 10 / 10 / 10 / 10; 
            secondDigit = number / 10 / 10 / 10 % 10;
            thirdDigit = number / 10 / 10 % 10;
            fourthDigit = number / 10 % 10;
            fifthDigit = number % 10;
            System.out.println("" + firstDigit + "" + secondDigit + "" + thirdDigit + "" + fourthDigit + "" + fifthDigit);
         }
        //You can probably see the pattern by now. It's not an elegant solution, but is very readable by even beginners:     
        if ((length == 6))
         {
            firstDigit = number / 10 / 10 / 10 / 10 / 10; //The first digit is divided by 10 for however many digits are after it
            secondDigit = number / 10 / 10 / 10 % 10;
            thirdDigit = number / 10 / 10 / 10 % 10;
            fourthDigit = number / 10 / 10 % 10;
            fifthDigit = number / 10 % 10; //The second to last always looks like this
            sixthDigit = number % 10;  //The last digit always looks like this no matter how big you go
            System.out.println("" + firstDigit + "" + secondDigit + "" + thirdDigit + "" + fourthDigit + "" + fifthDigit + "" + sixthDigit);
         }
        if ((length > 6))
         {
            //The main problem with this approach is that you have to define in advance how many digits you are working with
            //So it's simple, but not very elegant, and requires something to catch unexpected input from the user.
            System.out.println("Invalid Input!");
         }
    
      }
    
    }
    

    As a program it just outputs exactly the number you type in, but as you can see it's doing it in a way that shows that it's able to separate the digits of user input so you can use it as a test for a simple program, but again, it's not as good as some of the other solutions here, it's just a readable approach that works well for beginners. It also accepts negatives just fine.

    Also: In a case where you start with a double you could use the following to convert to int and truncate decimals:

    numberInt = (int)number;
    
    0 讨论(0)
  • 2020-11-28 13:55
    int a = 354;
    int b = (int)(a / Math.Pow(10, (int)Math.Log10(a))); // 3
    
    0 讨论(0)
  • 2020-11-28 13:56

    This way worked for me just fine, but it does involve converting from int to string and back to int.

    Integer.parseInt(String.valueOf(x).substring(0,1));
    
    0 讨论(0)
  • 2020-11-28 13:58

    Updated: log10 solution:

    A variation on the log10 solution with no division.:

    public int getFirstDigit(int x) {
        double e = Math.log10(Math.abs((long) x));
        return Double.valueOf(Math.pow(10.0, e - Math.floor(e))).intValue());
    }
    

    What's it doing?

    1. cast the int to long (to handle the MIN_VALUE issue)
    2. get the absolute value
    3. calculate the log10
    4. calculate the floor of the log10
    5. subtract the floor from the log10 (the difference will be the fraction)
    6. raise ten to the difference, giving you the value of the first digit.

    while loop solution:

    To handle Integer.MIN_VALUE and keep Math.abs() and the cast to long out of the loop:

    public static int getFirstDigit(int i) {
        i = Math.abs(i / (Math.abs((long)i) >= 10 ) ? 10 : 1);
        while (i >= 10 ) 
            i /= 10;
        return i;
    }
    
    0 讨论(0)
提交回复
热议问题