🧠 Count the Digits That Divide a Number | Python Problem Statement Given an integer n, return the number of digits in n that evenly divide n. 📌 Examples Input: n=248 Output: 3 Explanation: 248 is divisible by 8, 4, 2, hence the output is 3 🔍 Approach 1. Extract the last digit using % 10 2. If the digit is non-zero and divides the original number, increment the count 3. Remove the last digit using // 10 4. Stop when the number becomes 0 🧪 Python Code def countDigits(num: int) -> int: original = num countNum = 0 while num > 0: digit = num % 10 if digit != 0 and original % digit == 0: countNum += 1 num //= 10 return countNum ⏱️ Complexity Time: O(log₁₀ n) Space: O(1) 🧩 Edge Cases (Interview Tip) 1. Digits equal to 0 → ignored (division by zero) 2. Single-digit numbers → handled naturally 3. Negative numbers → clarify constraint or use abs(n) #Python #DSA #CodingInterview #InterviewPreparation #CollegeStudents #CampusPlacements #LearningInPublic
Count Divisible Digits in Number
More Relevant Posts
-
Understanding the def function in Python The def function in Python is used to define a function (a structured block of code) that can be reused to perform specific tasks, improving code efficiency and readability. Syntax The basic syntax for defining a function involves the def keyword, a function name, parentheses for optional parameters, and a colon. The function body must be indented. def function_name(parameter1, parameter2): # Function body (indented code block) # Perform operations return result # Optional: returns a value The def function is essential for breaking down complex tasks into small, manageable pieces. Example: Calculate doughnut volume #Import math library import math # Define the function def doughnut_volume(r, R): vol_result = (2*math.pi*((R+r)/2))*(math.pi*(((R-r)/2)**2)) return vol_result # Call the function and store the result volume = doughnut_volume(10, 15) # Print the result print(f"The doughnut volume is: {volume}")
To view or add a comment, sign in
-
A Python f-string (formatted string literal) is a way to embed expressions directly inside string constants, introduced in Python 3.6. It makes it easy to insert variable values into strings without needing concatenation or the .format() method. Syntax: name = "Sam" age = 30 print(f"My name is {name} and I am {age} years old.") Output: My name is Sam and I am 30 years old. How it works: The f before the opening quote tells Python to interpret the string as an f-string. Expressions inside {} are evaluated and replaced with their values. Benefits: Clean and readable More concise than using + or .format() You can use any valid Python expression inside the {} (e.g. {age + 5}, {name.upper()}) #Python #f-strings
To view or add a comment, sign in
-
-
Here’s a small Python program that works like a polite bouncer at a party 😄 — it only lets unique guests in and politely ignores duplicates! 🧠 What this code does: We create a function unique(li) that: Takes a list as input Checks each item one by one Adds it to a new list only if it hasn’t appeared before 📌 Input: lst = [1,2,3,1,2,4] 🎯 Output: [1, 2, 3, 4] Why this is useful for beginners: ✔ Understand lists in Python ✔ Learn how loops work ✔ Practice conditional logic (if i not in ...) ✔ Build problem-solving skills Simple logic, powerful concept, and super useful in real-world coding 🚀 lst = [1,2,3,1,2,4] def unique(li): uniquelist =[] for i in li: if i not in uniquelist: uniquelist.append(i) return uniquelist unq = unique(lst) print(unq) #Python #Coding #Programming #BeginnerToPro #DataScience #LearnWithFun
To view or add a comment, sign in
-
-
🧠 Python Feature That Feels Like a Cheat Code: enumerate() Most beginners write this 👇 i = 0 for item in items: print(i, item) i += 1 But Python says… why work so hard? 😌 ✅ Pythonic Way for i, item in enumerate(items): print(i, item) 🧒 Simple Explanation Imagine numbering students in a line 🧑🎓 enumerate() gives you: ✨ the number ✨ the student at the same time 🎯 💡 Why It’s Important ✔ Cleaner code ✔ Fewer bugs ✔ More readable ✔ Very common in interviews ⚡ Bonus Tip Start counting from 1: for i, item in enumerate(items, start=1): print(i, item) ✔️ Python rewards clean thinking. ✔️ If you’re manually counting in a loop… Python already has a better way 🐍✨ #Python #PythonTips #CleanCode #LearnPython #DeveloperLife #Coding
To view or add a comment, sign in
-
-
Do you want to identify which lines use the most amount of memory in your Python script? Try 𝗺𝗲𝗺𝗼𝗿𝘆_𝗽𝗿𝗼𝗳𝗶𝗹𝗲𝗿. 𝗺𝗲𝗺𝗼𝗿𝘆_𝗽𝗿𝗼𝗳𝗶𝗹𝗲𝗿 is a Python module to make a line-by-line analysis of memory consumption for Python functions. Below you can see how to use memory_profiler within your Python script: • Decorate the function you want to profile with @𝗽𝗿𝗼𝗳𝗶𝗹𝗲. • Run the script by passing the option -𝗺 𝗺𝗲𝗺𝗼𝗿𝘆_𝗽𝗿𝗼𝗳𝗶𝗹𝗲𝗿 to load the 𝗺𝗲𝗺𝗼𝗿𝘆_𝗽𝗿𝗼𝗳𝗶𝗹𝗲𝗿 module. Link to project: pypi(dot)org/project/memory-profiler --- ♻️ Found this useful? Share it with another builder. ➕ For daily practical AI and Python posts, follow Banias Baabe.
To view or add a comment, sign in
-
-
1) Create a program to check if a given number is even or odd. # Problem Statement: Create a program to check if a given number is even or odd. # Simple Python Program: # get user input num = int(input("Enter a number: ")) # check if number is even or odd if num % 2 == 0: print(num, "is an even number") else: print(num, "is an odd number") # Explanation: # First, we prompt the user to enter a number using the input() function and store it in the variable "num". Then, we use the modulus operator (%) to check if the number is divisible by 2 or not. If the remainder is 0, then the number is even, otherwise it is odd. Finally, we print the appropriate message based on the condition. # Sample Input and Output: # Enter a number: 7 # 7 is an odd number
To view or add a comment, sign in
-
🐍 Python Tip: = vs == in if statements A common beginner mistake in Python is using = instead of == inside if conditions. = → assignment == → comparison Inside if / elif, Python expects a boolean expression, not an assignment. ❌ Wrong: if score >= 90 and project = True: print("A") ✅ Correct (Pythonic): if score >= 90 and project: print("A") 🧠 Tip: If a variable is already boolean, don’t compare it to True. Just use it. Small detail, big difference. #Python #PythonProgramming #LearnPython #Coding #Programming #SoftwareDevelopment #DataAnalytics #DataScience #TechCareers #CodingTips #BeginnerTips #CleanCode #PythonTips #DeveloperLife
To view or add a comment, sign in
-
🚀 Learning Python String Methods — My Practice Notes Today I practiced important Python string functions that help in text processing and formatting. These methods are very useful in real projects and data handling. ✔ upper() → converts text to uppercase ✔ lower() → converts text to lowercase ✔ rstrip() → removes characters from right side ✔ replace() → replaces words in a string ✔ split() → splits string into list ✔ capitalize() → capitalizes first letter ✔ center() → aligns text at center with given width ✔ count() → counts occurrences of a word ✔ startswith() → checks starting text ✔ endswith() → checks ending text ✔ find() → finds position of a word ✔ swapcase() → swaps upper/lower case ✔ title() → capitalizes each word Practicing these methods helped me understand how powerful Python strings are for real-world applications. #Python #LearningPython #CodingPractice #StringMethods #BeginnerToPro https://lnkd.in/gYptz5A4
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development