Programming Tricks

How to Find the Sum of 1 to 100, and Its Variants

Legend has it that the German Mathematician, Carl Friedrich Gauss, who was an elementary student during the late 1700s, showed his teacher how quickly he summed up the numbers 1 to 100 by using a simple mathematical trick.

Centuries later, most programmers are still doing it the long way!

Techniques How to Remove Any Recursion

A function that calls itself is hard to visualize for most developers. Common software requirements are implemented thru loops, arrays, variables, and automated function calls thus making the use of recursion and variations of the list data structure unusual. In this article, we will take a look at how we can remove any recursive program by following the simple techniques described below. It is very important to understand that this article is not saying that recursion is bad.

How to Swap Two Variables Without a Third Variable?

One of the most common whiteboarding questions is "Swapping of two (2) integers without using a third variable". The objective is not to optimize the standard way of swapping variables but rather to show the resourcefulness of the applicant given problems with constraints. Because in real life, you'll face challenges where you have to work on projects with limited resources.

But how do we approach this problem? The computer operations available are:

How to Find the Larger Number Without Conditional Operators Part 2 (Arithmetic)

Given two (2) signed integer numbers, A and B. Find the larger number between these two (2) variables, using only arithmetic expressions. Provide a solution to the following:

  1. Assign 0 to X, if A = B, or assign the larger number between A and B
  2. Assign the larger number between A and B to Y, or assign either A or B, if A = B

How to Find the Larger Number Without Conditional Operators Part 1 (Using Bitwise Operators)

Given two (2) signed integer numbers, A and B, where:

  • size = ( Integer size int = 4 bytes* = 32 bits ) - 1
  • -2size ≤ A ≤ 2size-1, and
  • -2size ≤ B ≤ 2size-1

Find the larger number between variables A and B, without using conditional operators. Provide a solution to the following:

  1. Assign 0 to X, if A = B, or assign the larger number between A and B
  2. Assign the larger number between A and B to Y, or assign either A or B, if A = B
Subscribe to RSS - Programming Tricks