Replace All Zeros With Ones

6
0

Given an integer N. Return the integer formed by replacing every digit 0 with 1 in the decimal representation of N.

Example 1

Input: N = 102003

Output: 112113

Explanation: Every 0 in 102003 is replaced with 1, resulting in 112113.

Example 2

Input: N = 204

Output: 214

Explanation: The 0 in 204 is replaced with 1, giving 214.

Approach

The main idea is to replace every 0 digit with 1 while keeping all other digits unchanged. The integer can first be converted into a string so that each digit can be accessed and checked easily.

A new string res can be used to store the modified number. This keeps the original digit order unchanged while replacing every occurrence of 0 with 1. Finally, the modified string is converted back into an integer and returned as the answer.

Algorithm

  • Convert the given integer into a string using to_string().

  • Initialize an empty string to store the modified number.

  • Traverse the string character by character.

  • If the current character is '0', replace it with '1'.

  • Otherwise, keep the current character unchanged.

  • Convert the modified string back into an integer using stoi() and return the result.

Dry Run

Replace All Zeros With Ones

Replace All Zeros With Ones

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to replace all 0s with 1s
int replaceZerosWithOnes(int N) {
// Convert the integer into a string
string s = to_string(N);
// Store the modified number
string res = "";
// Traverse each character of the string
for (char ch : s) {
// Replace 0 with 1
if (ch == '0') {
res += '1';
}
// Keep other digits unchanged
else {
res += ch;
}
}
// Convert the modified string back to an integer
return stoi(res);
}
};
// Driver code starts
int main() {
Solution sol;
cout << sol.replaceZerosWithOnes(102003) << endl;
return 0;
}

Complexity Analysis

• Time Complexity: O(D), where D represents the number of digits in the given integer. Each digit is visited exactly once while building the modified string.

• Space Complexity: O(D), as an additional string is used to store the modified digits.

Interview follow-up Questions

Yes. Each digit can be extracted using modulo and division, replaced when it is 0, and then used to reconstruct the number. However, the string-based approach is simpler and easier to understand.

StringTCS NQT

Read Similar Blogs

Comments0