Arham Rumi

Posted on

# Replacing Digits in a Number Without Converting to String

In technical interviews, candidates are often challenged with problems that require creative solutions and efficient problem-solving techniques. One such problem is replacing occurrences of a digit in a number without converting the number to a string or using string operations. In this article, we'll explore a simple solution to this problem using JavaScript.

Problem Statement:
Given a number and two digits (one to be replaced and one to replace with), the task is to replace all occurrences of the digit to be replaced in the number with the replacement digit without converting the number to string or using string operation.

Solution:
We'll approach this problem by iterating through each digit of the number and replacing the specified digit without converting the number to a string. Here's how we'll do it:

1. Determine the length of the number to set the limit of the divisor.
2. Initialize a new number variable to store the result.
3. Iterate through each digit of the number using a while loop.
4. Extract the first digit of the remaining number by dividing it with the current divisor.
5. If the extracted digit matches the digit to be replaced, replace it with the replacement digit.
6. Multiply the modified digit with the current divisor to get its place value.
7. Add the modified digit to the new number.
8. Update the original number by taking the remainder after division by the divisor.
9. Reduce the divisor by a factor of 10 to move to the next digit.
``````let num = 34645644; // Original Number
let digit_to_be_replaced = 4; // Digit to be replaced
let digit_replace_with = 7; // Digit to replace with
let len = Math.ceil(Math.log10(num + 1)); // Length of the number
let lim = 10 ** (len - 1); // Divisor
let new_num = 0; // New number

// Loop through each digit of the number
while (num) {
let quotient = Math.floor(num / lim); // Extract the first digit
// Check if the digit matches the digit to be replaced
if (quotient == digit_to_be_replaced) {
quotient = digit_replace_with; // Replace the digit
}
quotient *= lim; // Multiply with place value
new_num += quotient; // Add to new number
num %= lim; // Update number
lim /= 10; // Reduce divisor
}

console.log("New Number:", new_num);
``````

Conclusion:
In this article, we've demonstrated a JavaScript solution to the problem of replacing occurrences of a digit in a number without converting the number to a string. By understanding the problem statement and applying an efficient algorithm, we've successfully solved the problem using only numerical operations. This approach demonstrates critical thinking and problem-solving skills, which are essential in technical interviews.

By practicing similar problems and understanding different problem-solving techniques, candidates can enhance their problem-solving abilities and improve their performance in technical interviews.