Friends, how to find out the first digit of an array element? I figured out the last one, but from the first difficulty.
for example, given the array a=[352, 234,745,853]
withdraw 3, 2, 7 ,8
Friends, how to find out the first digit of an array element? I figured out the last one, but from the first difficulty.
for example, given the array a=[352, 234,745,853]
withdraw 3, 2, 7 ,8
The version of Vladimir Martyanov from the comments (about converting to a string and selecting a character in the first position) is good.
Alternatively, you can do this:
Math.pow returns a double )Such code:
int a[] = {352, 2354,745,853}; for (int i : a) { if (i==0) { System.out.println(0); continue; } if ( i == Integer.MIN_VALUE ) { System.out.println(2); continue; } System.out.println(i / (int)Math.pow(10, ((int)(Math.log10(Math.abs(i)))))); } Output:
3 2 7 8 As suggested by @VladD, you need to separately consider the case of Integer.MIN_VALUE . The fact is that Math.abs with i < 0 returns -i , and for int it is already going beyond 2147483647. Therefore, the number returns to its negative position.
Math.log10(Math.abs(i)) will crash in one tricky case :) - VladDAnother option:
Code:
int a[] = {352, 2354, 745, 853}; for (int i : a) { // если число может быть отрицательным, добавляем следующую строку. i = Math.abs(i) while (i >= 10) { i = i / 10; } System.out.println(i); } 3 2 7 8 I hope to output in one line and with random commas ( 3, 2, 7 ,8 ) is this not a mandatory requirement? =)
i = Math.abs(i) not quite true. Guess what value i ? - VladDImplementation based on Integer.toString and company. In principle, the same logarithm, but according to the table.
final static int[] placements = new int[] { 0, 9, 99, 999, 9_999, 99_999, 999_999, 9_999_999, 99_999_999, 999_999_999, Integer.MAX_VALUE }; static int firstDigit( int number ) { // т.к. Math.abs( Integer.MIN_VALUE ) == Integer.MIN_VALUE // выносим в отдельную проверку if ( number == Integer.MIN_VALUE ) return 2; number = Math.abs( number ); int position = 1; while ( number > placements[position] ) { position++; } return number / (placements[position-1]+1); } public static void main(String args[]) { int a[] = {352, 2354, 745, 853}; // Ня! Стримы! System.out.println( Arrays.stream( a ).map( n -> firstDigit( n ) ) .mapToObj( Integer::toString ).collect( Collectors.joining( ", " ) ) ); } for( int n = 0; n <= Integer.MAX_VALUE; n++ ) process during the test for( int n = 0; n <= Integer.MAX_VALUE; n++ ) :) - zRrrSource: https://ru.stackoverflow.com/questions/470860/
All Articles