Reverse bits of an integer

Algorithm goal


(this is © from

Scala Concepts & Hints

Def Inside Def

A great aspect of Scala is being able to declare functions inside functions, making it possible to reduce repetition.

def exampleDef(input: String): String = {
  def surroundInputWith(char: Char): String = s"$char$input$char"

It is also frequently used in combination with Tail Recursion.

Stack Safety

Stack safety is present where a function cannot crash due to overflowing the limit of number of recursive calls.

This function will work for n = 5, but will not work for n = 2000 (crash with java.lang.StackOverflowError) - however there is a way to fix it :-)

In Scala Algorithms, we try to write the algorithms in a stack-safe way, where possible, so that when you use the algorithms, they will not crash on large inputs. However, stack-safe implementations are often more complex, and in some cases, overly complex, for the task at hand.

def sum(from: Int, until: Int): Int =
  if (from == until) until else from + sum(from + 1, until)

def thisWillSucceed: Int = sum(1, 5)

def thisWillFail: Int = sum(1, 300)

Read more

Tail Recursion

In Scala, tail recursion enables you to rewrite a mutable structure such as a while-loop, into an immutable algorithm.

def fibonacci(n: Int): Int = {
  def go(i: Int, previous: Int, beforePrevious: Int): Int =
    if (i >= n) previous else go(i + 1, previous + beforePrevious, previous)

  go(i = 1, previous = 1, beforePrevious = 0)

assert(fibonacci(8) == 21)

Read more

Algorithm in Scala

22 lines of Scala (version 2.13), showing how concise Scala can be!

This solution is available for access!


'Unlimited Scala Algorithms' gives you access to all the Scala Algorithms!

Upon purchase, you will be able to Register an account to access all the algorithms on multiple devices.

Test cases in Scala

assert(bitsOf(50) == "00000000000000000000000000110010")
assert(bitsOf(-50) == "11111111111111111111111111001110")
assert(bitsOf(reverse(-50)) == "01110011111111111111111111111111")
assert(bitsOf(reverse(50)) == "01001100000000000000000000000000")
    val num = scala.util.Random.nextInt()
    reverse(num) == java.lang.Integer.reverse(num)
  "Our reverse acts the same as Java's reverse for any int"
    val num = scala.util.Random.nextInt()
    reverseO1(num) == java.lang.Integer.reverse(num)
  "Reverse O(1) acts the same as Java's reverse for any int"
def bitsOf(int: Int): String = ???

def reverse(int: Int): Int = ???

def reverseO1(a: Int): Int = ???