Improved the algorithm of changeVal function.