日期:2014-05-20  浏览次数:20722 次

算法题
给定一个数字n,如果n是偶数就让n/2,如果是奇数就让n +1或-1,例
n = 31;
n = n - 1; //30
n = n / 2; //15
n = n + 1; //16
n = n / 2; //8
n = n / 2; //4
n = n / 2; //2
n = n / 2; //1
问:怎样能够以最少的计算次数,算出n = 1;

------解决方案--------------------
不知道这样可以么?

Java code
public class Test1 {

    public static void main(String[] args) {
        int n = 31;
        
        if(n < 1) {
            return;
        }
        int count = 0;        
        while(n != 1) {            
            if(n % 2 == 0) {
                n /= 2;                
            } else {
                if((n & 2) == 0 || n == 3) {
                    n--;
                } else {
                    n++;
                }
            }
            count++;
            System.out.println(count + ": " + n);
        }
        System.out.println("Total: " + count);
    }
}