mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
added numberOfDigitsUsingLog method (#1364)
* added numberOfDigitsUsingLog method * added JSDoc comment --------- Co-authored-by: madhuredra <madhuredra.tiwari@zemosolabs.com>
This commit is contained in:

committed by
GitHub

parent
268796b0e8
commit
6ad5b9c2b1
@ -9,4 +9,14 @@
|
||||
|
||||
const numberOfDigit = (n) => Math.abs(n).toString().length
|
||||
|
||||
export { numberOfDigit }
|
||||
/**
|
||||
* Returns the number of digits of a given integer.
|
||||
*
|
||||
* @param {number} n - The integer for which to count digits.
|
||||
* @returns {number} The number of digits in the integer.
|
||||
* @see https://math.stackexchange.com/questions/2145480/how-does-the-logarithm-returns-the-number-of-digits-of-a-number
|
||||
* @author dev-madhurendra
|
||||
*/
|
||||
const numberOfDigitsUsingLog = (n) => n === 0 ? 1 : Math.floor(Math.log10(Math.abs(n))) + 1
|
||||
|
||||
export { numberOfDigit, numberOfDigitsUsingLog }
|
||||
|
@ -1,4 +1,4 @@
|
||||
import { numberOfDigit } from '../NumberOfDigits'
|
||||
import { numberOfDigit, numberOfDigitsUsingLog } from '../NumberOfDigits'
|
||||
|
||||
describe('NumberOfDigits', () => {
|
||||
it('should return the correct number of digits for an integer', () => {
|
||||
@ -8,4 +8,13 @@ describe('NumberOfDigits', () => {
|
||||
it('should return the correct number of digits for a negative number', () => {
|
||||
expect(numberOfDigit(-2346243)).toBe(7)
|
||||
})
|
||||
|
||||
it.each([
|
||||
[0, 1],
|
||||
[123423232, 9],
|
||||
[-123423232, 9],
|
||||
[9999, 4]
|
||||
])('should return the correct number of digits in an integer', (value, expected) => {
|
||||
expect(numberOfDigitsUsingLog(value)).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
Reference in New Issue
Block a user