952. 数字问题

描述

给一个转换规则来转换数字n:
n是奇数,n = 3n + 1
n是偶数,n = n / 2
经过若干次转换后,n会变成1。

现在给一个n,输出它转换到1需要的次数。

1 <= n <= 1000000

您在真实的面试中是否遇到过这个题?

样例

给出 n = 2, 返回 1.

解释:
2→1

给出 n = 3, 返回 7.

解释:
3→10→5→16→8→4→2→1
Description
Give a conversion rule to convert number n:

n is an odd number: n = 3 * n + 1
n is an even number: n = n / 2
After several conversions, n will become 1.
Given a number n, find the times of converting to 1.
public class Solution {
    /**
     * @param n: the number n 
     * @return: the times n convert to 1
     */
    public int digitConvert(int n) {
        // Write your code here 
        int count = 0;
        long newN = (long) n;

        while(newN!=1){
            if (newN % 2 ==1){
                newN = 3*newN +1;
            }else {
                newN = newN / 2;
            }
            count ++;
        }
        
        return count;
    }
}
public class Solution {
    /**
     * @param n: the number n 
     * @return: the times n convert to 1
     */
    public int digitConvert(int n) {
        // Write your code here 
    
        int res = 0;
        while(n != 1){
            if(n % 2 == 0){
                n = n >> 1;
                
            }else {
                n = 3 * n + 1;
            }
            res++;
        }
        return res;
    }
}

转载于:https://www.cnblogs.com/browselife/p/10645605.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值