鱼C论坛

 找回密码
 立即注册
查看: 1199|回复: 0

数字问题

[复制链接]
发表于 2020-1-22 19:18:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
给一个转换规则来转换数字 n:

n 是奇数,n = 3n + 1
n 是偶数,n = n / 2
经过若干次转换后,n 会变成 1。

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


Python 66 ms :

  1. class Solution:
  2.     def digitConvert(self, n):
  3.         r = 0
  4.         while n != 1:
  5.             n = (3 * n + 1 if n % 2 else n // 2)
  6.             r += 1
  7.         return r
复制代码


C++ 11 ms :

  1. class Solution
  2. {
  3. public:
  4.     /**
  5.      * @param n: the number n
  6.      * @return: the times n convert to 1
  7.      */
  8.     int digitConvert(int n)
  9.     {
  10.         int r = 0;
  11.         while (n != 1)
  12.         {
  13.             n = (n % 2 ? 3 * n + 1 : n / 2);
  14.             r++;
  15.         }
  16.         return r;
  17.     }
  18. };
复制代码


JavaScript 202 ms :

  1. /**
  2. * @param n: the number n
  3. * @return: the times n convert to 1
  4. */
  5. function digitConvert(n) {
  6.     var r = 0;
  7.     while (n != 1) {
  8.         n = (n % 2 ? 3 * n + 1 : n / 2);
  9.         r++;
  10.     }
  11.     return r;
  12. }
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 15:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表