Skip to content

Commit c7e9133

Browse files
committed
Added codeto check if a number is power of 2
1 parent 64e57a7 commit c7e9133

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.scala.powerof2
2+
3+
import scala.annotation.tailrec
4+
5+
object PowerOfTwo {
6+
7+
def isPowerOfTwoByDivision(num: Long): Boolean = {
8+
@tailrec
9+
def isPowerRec(n: Long): Boolean = {
10+
if (n == 1) true
11+
else if (n % 2 == 0) isPowerRec(n / 2)
12+
else false
13+
}
14+
num > 0 && isPowerRec(num)
15+
}
16+
17+
def isPowerOfTwoByCountingOnes(num: Long): Boolean = {
18+
num > 0 && num.toBinaryString.count(_ == '1') == 1
19+
}
20+
21+
def isPowerOfTwoByBitwiseAnd(num: Long): Boolean = {
22+
num > 0 && (num & (num - 1)) == 0
23+
}
24+
25+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.baeldung.scala.powerof2
2+
3+
import org.scalacheck.Gen
4+
import org.scalatest.flatspec.AnyFlatSpec
5+
import org.scalatest.matchers.should.Matchers
6+
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
7+
8+
class PowerOfTwoUnitTest
9+
extends AnyFlatSpec
10+
with Matchers
11+
with ScalaCheckPropertyChecks {
12+
13+
private val powerOfTwoFunctions = Seq(
14+
("Division", PowerOfTwo.isPowerOfTwoByDivision),
15+
("Counting Ones", PowerOfTwo.isPowerOfTwoByCountingOnes),
16+
("Bitwise AND", PowerOfTwo.isPowerOfTwoByBitwiseAnd)
17+
)
18+
19+
powerOfTwoFunctions.foreach { (desc, fn) =>
20+
it should s"[$desc] return true for a number that is power of 2" in {
21+
val powersOfTwo: Gen[Long] =
22+
Gen.choose(0, 62).map(n => Math.pow(2, n).toLong)
23+
forAll(powersOfTwo) { num =>
24+
fn(num) shouldBe true
25+
}
26+
}
27+
28+
it should s"[$desc] return false for a number that is NOT a power of 2" in {
29+
val powersOfTwo: Gen[Long] =
30+
Gen.choose(0, 62).map(n => Math.pow(2, n).toLong)
31+
val notPowerOf2 = Gen
32+
.choose(0L, Long.MaxValue)
33+
.suchThat(n => !powersOfTwo.sample.contains(n))
34+
forAll(notPowerOf2) { num =>
35+
fn(num) shouldBe false
36+
}
37+
}
38+
39+
it should s"[$desc] return false for any negative numbers" in {
40+
val negativeNumbers = Gen.choose(Long.MinValue, 0L)
41+
forAll(negativeNumbers) { num =>
42+
fn(num) shouldBe false
43+
}
44+
}
45+
}
46+
47+
}

0 commit comments

Comments
 (0)