Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6ad5b9c

Browse files
dev-madhurendramadhuredra
and
madhuredra
authored
added numberOfDigitsUsingLog method (TheAlgorithms#1364)
* added numberOfDigitsUsingLog method * added JSDoc comment --------- Co-authored-by: madhuredra <madhuredra.tiwari@zemosolabs.com>
1 parent 268796b commit 6ad5b9c

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

‎Maths/NumberOfDigits.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,14 @@
99

1010
const numberOfDigit = (n) => Math.abs(n).toString().length
1111

12-
export { numberOfDigit }
12+
/**
13+
* Returns the number of digits of a given integer.
14+
*
15+
* @param {number} n - The integer for which to count digits.
16+
* @returns {number} The number of digits in the integer.
17+
* @see https://math.stackexchange.com/questions/2145480/how-does-the-logarithm-returns-the-number-of-digits-of-a-number
18+
* @author dev-madhurendra
19+
*/
20+
const numberOfDigitsUsingLog = (n) => n === 0 ? 1 : Math.floor(Math.log10(Math.abs(n))) + 1
21+
22+
export { numberOfDigit, numberOfDigitsUsingLog }

‎Maths/test/NumberOfDigits.test.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { numberOfDigit } from '../NumberOfDigits'
1+
import { numberOfDigit,numberOfDigitsUsingLog } from '../NumberOfDigits'
22

33
describe('NumberOfDigits', () => {
44
it('should return the correct number of digits for an integer', () => {
@@ -8,4 +8,13 @@ describe('NumberOfDigits', () => {
88
it('should return the correct number of digits for a negative number', () => {
99
expect(numberOfDigit(-2346243)).toBe(7)
1010
})
11+
12+
it.each([
13+
[0, 1],
14+
[123423232, 9],
15+
[-123423232, 9],
16+
[9999, 4]
17+
])('should return the correct number of digits in an integer', (value, expected) => {
18+
expect(numberOfDigitsUsingLog(value)).toBe(expected)
19+
})
1120
})

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /