Skip to content

Commit 9f6eee1

Browse files
committed
Added one more method to check power of 2
1 parent c7e9133 commit 9f6eee1

File tree

2 files changed

+6
-1
lines changed

2 files changed

+6
-1
lines changed

scala-core-modules/scala-core-9/src/main/scala/com/baeldung/scala/powerof2/PowerOfTwo.scala

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,8 @@ object PowerOfTwo {
2222
num > 0 && (num & (num - 1)) == 0
2323
}
2424

25+
def isPowerOfTwoByLazyList(num: Long): Boolean = {
26+
num > 0 && LazyList.iterate(num)(_ / 2).takeWhile(_ > 1).forall(_ % 2 == 0)
27+
}
28+
2529
}

scala-core-modules/scala-core-9/src/test/scala/com/baeldung/scala/powerof2/PowerOfTwoUnitTest.scala

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ class PowerOfTwoUnitTest
1313
private val powerOfTwoFunctions = Seq(
1414
("Division", PowerOfTwo.isPowerOfTwoByDivision),
1515
("Counting Ones", PowerOfTwo.isPowerOfTwoByCountingOnes),
16-
("Bitwise AND", PowerOfTwo.isPowerOfTwoByBitwiseAnd)
16+
("Bitwise AND", PowerOfTwo.isPowerOfTwoByBitwiseAnd),
17+
("LazyList", PowerOfTwo.isPowerOfTwoByLazyList)
1718
)
1819

1920
powerOfTwoFunctions.foreach { (desc, fn) =>

0 commit comments

Comments
 (0)