remove the repeated numbers in a number for ex:12234 output is 1234 in python code
- User
remove the repeated numbers in a number for ex:12234 output is 1234 in python code
- Assistant
You can remove the repeated numbers from a number by converting it to a string, iterating through the characters, and adding only the unique characters to a new string or list. Here is a Python function that accomplishes this:
def remove_repeated_numbers(num): # Convert the number to a string num_str = str(num) # Initialize an empty list to store unique characters result = [] # Loop through each character in the string representation of the number for char in num_str: # If the character is not already in the result list, add it if char not in result: result.append(char) # Join the list into a string and convert it back to an integer return int(''.join(result)) # Example usage num = 12234 print(remove_repeated_numbers(num)) # Output: 1234This function constructs a list of unique digits as it iterates over the number's string representation and returns the reconstructed number with duplicates removed.
- User
remove the repeated numbers in a number for ex:12234 output is 1234 without converting into string in python
- Assistant
To remove repeated numbers from a number without converting it to a string, you can work with the number in its numeric form. One way to do this is by repeatedly extracting the least significant digit and building the result using only the unique digits. Here is a solution:
def remove_repeated_numbers(num): seen_digits = set() result = 0 place = 1 while num > 0: # Find the last digit of num digit = num % 10 # Check if the digit has been seen before if digit not in seen_digits: # Add to the result in the correct place value result += digit * place place *= 10 # Mark this digit as seen seen_digits.add(digit) # Remove the last digit num //= 10 # Reversing the result because the digits were extracted in reverse order final_result = 0 while result > 0: final_result = final_result * 10 + result % 10 result //= 10 return final_result # Example usage num = 12234 print(remove_repeated_numbers(num)) # Output: 1234