Monday, June 6, 2016

Java Challenge - sumDigits Recursive

Given a non-negative int n, return the sum of its digits recursively (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).

sumDigits(126) → 9
sumDigits(49) → 13
sumDigits(12) → 3

Hisoka's Trick :
1
2
3
4
public int sumDigits(int n) {
   if(n < 10) return n;
   return n%10 + sumDigits(n/10);
}

Test Result:

Java Challenge - Triangle Recursive

We have triangle made of blocks. The topmost row has 1 block, the next row down has 2 blocks, the next row has 3 blocks, and so on. Compute recursively (no loops or multiplication) the total number of blocks in such a triangle with the given number of rows.

triangle(0) → 0
triangle(1) → 1
triangle(2) → 3

Hisoka :
1
2
3
4
public int triangle(int rows) {
  if (rows == 0) return 0;
  return rows+triangle(rows-1);
}

Test Result: