forked from aayushi-droid/Python-Thunder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rearrangeTheNumber.py
72 lines (47 loc) · 1.58 KB
/
rearrangeTheNumber.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'''
Problem Task : Given a number, return the difference between the maximum and minimum numbers that can be formed when the digits are rearranged.
Problem Link : https://edabit.com/challenge/jwzAdBnJnBxCe4AXP
'''
def maximumNum(num):
# Hashed array to store count of digits
count = [0 for x in range(10)]
# Connverting given number to string
string = str(num)
# Updating the count array
for i in range(len(string)):
count[int(string[i])] = count[int(string[i])] + 1
# Result stores final number
result = 0
multiplier = 1
# traversing the count array
# to calculate the maximum number
for i in range(10):
while count[i] > 0:
result = result + ( i * multiplier )
count[i] = count[i] - 1
multiplier = multiplier * 10
# return the result
return result
def minNum(num):
#initialize frequency of each digit to Zero
freq=[0 for x in range(10)]
#count frequency of each digit in the number
while (num):
d = num % 10 # extract last digit
freq[d]++ #increment counting
num = num / 10 #remove last digit
#Set the LEFTMOST digit to minimum expect 0
result = 0
for i in range(0,10):
if (freq[i]):
result = i
freq[i]--
break
// arrange all remaining digits
// in ascending order
for i in range(0,10):
while (freq[i]--):
result = result * 10 + i
return result
def rearrangeNumber(num):
return maximumNum(num)-minNum(num)