Replacing 0s with 1s in an Integer: 2 Approaches

Day 21 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Replace all 0’s with 1 in a given integer We were given an integer. Task was simple. Replace every 0 with 1. At first it looked very basic. But there were two ways to approach it. Let’s understand it simply. ◾️Imagine a number written on paper. ◾️Whenever you see a 0, you overwrite it with 1. ◾️All other digits remain the same. That’s the idea. --- 💻 Approach 1 (Using String) 🔹️Convert the integer to a string. 🔹️Traverse each character. 🔹️If character is '0', replace it with '1'. 🔹️Convert the string back to integer. Very simple. Easy to implement. 💻 Approach 2 (Using Arithmetic) This avoids string conversion. 🔹️Extract digits using n % 10. 🔹️If digit is 0, change it to 1. 🔹️Build a new number using multiplication and addition. 🔹️Reverse it again to maintain correct order. More number manipulation involved. 📊 Complexity Analysis Time Complexity: O(D) Where D is number of digits. Space Complexity: O(1) Only few variables used. 📚 What I learned today: ▫️Simple problems can have multiple approaches. ▫️String operations make digit problems easier. ▫️Arithmetic manipulation gives more control over digits. ▫️Understanding both approaches improves problem solving. Day 21 completed. Learning small tricks every day 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic

To view or add a comment, sign in

Explore content categories