描述
给一个转换规则来转换数字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;
}
}