Slightly modified the algorithm so now it also removes unnecessary 0s