Skip to content

added numberOfDigitsUsingLog method #1364

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion Maths/NumberOfDigits.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
11 changes: 10 additions & 1 deletion Maths/test/NumberOfDigits.test.js
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand All @@ -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)
})
})
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy