2 min read ~ Hello readers! It’s really important for me to continue my practice and learning. Every week, I block off 30 minutes, set a timer and choose a challenge from codewars. This helps me keep my skills sharp, see how other devs all over the planet would solve these problems, and take some leisure time to problem solve and be creative. Being able to see other solutions expands my mind for solving future problems in a clever and efficient way. Today, the problem set focuses on Python.
Given an array of integers of any length, return an array that has 1 added to the value represented by the array.
- the array can’t be empty
- only non-negative, single digit integers are allowed
Return nil
(or your language’s equivalent) for invalid inputs.
Examples
For example the array [2, 3, 9]
equals 239
, adding one would return the array [2, 4, 0]
.
[4, 3, 2, 5]
would return [4, 3, 2, 6]
Solution:
def up_array(arr):
if not arr or any(x < 0 or x > 9 for x in arr):
return None
str_lst = [str(numb) for numb in arr] #convert arr into list of strings
int_conv = int("".join(str_lst)) + 1 #join and convert the number while adding 1 to the total
return [int(x) for x in str(int_conv)] #return an array of int with the newly constructed total
All solutions are also now on my GitHub profile if you want to check out all of the coding challenges I’ve completed so far!
All credit to problem sets goes to codewars