到达一个数字

https://www.lintcode.com/problem/reach-a-number/description

public class Solution {
    /**
     * @param target: the destination
     * @return: the minimum number of steps
     */
    public int reachNumber(int target) {
        // Write your code here
        target = Math.abs(target);
//        两个方向上操作方式相反,可以归结为一个
        int step = 1;
        int position = 0;
        while (true) {
            position += step;
            if (position == target) {
                return step;
            } else if (position > target) {
                position -= target;
//                多出了这么多步,position必然小于step,否则就没有最后一步的必要 。
                if (position % 2 == 0) {
//                    如果差值是偶数,只需要一个数反向,假设这个数为n, 其实少的是-2n.所以必须为偶数。
                    return step;
                } else {
//                   如果差值是奇数,想办法变成偶数、
                    if ((step + 1) % 2 == 0) {
//                        下一步是偶数,需要两步才能制造出一个奇数
                        return step + 2;
                    } else {
//                        下一步是奇数,直接可以让差值变成偶数
                        return step + 1;
                    }
                }
            }
            step++;
        }

    }

}

你可能感兴趣的:(到达一个数字)