Programming interview questions and answers

Compress a string

Write a program to compress a string. If input is “aabbb” expected output is “a2b3” The approach:- Have 2 pointers read and write to the input string. Scan the string using read pointer. If similar characters are seen keep incrementing a count. If character sequence changes, write the character and the count value at the …

Compress a string Read More »

Convert decimal number to hexadecimal

Write a program to convert decimal number to hexadecimal The approach:- Initialize a string array to hold the output hexadecimal string. mod the input number by 16.  Map a hexadecimal digit based on the reminder value and append the output string. Divide the number by 16 for next iteration. Repeat steps 2 and 3 till …

Convert decimal number to hexadecimal Read More »

Convert binary string to decimal number

Write a program to convert binary string to decimal number Parse the input string till end. On encountering a “1” compute power of 2 for the current position and add to a variable holding the result. C++ program to convert binary string to decimal number #include <iostream>#include <cstring>#include <cstdlib>#include <cmath>using namespace std;int bin2dec(char* str) {int …

Convert binary string to decimal number Read More »

Find the longest palindrome in a string

Write a program to find the longest palindrome in a string The approach:- From each character location, compare the left and right locations for equality. Remember the location and maximum size of equality. Print the string starting from the location minus maximum size to location plus maximum size, which is the longest palindrome. C++ program …

Find the longest palindrome in a string Read More »