博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Write an Efficient Method to Check if a Number is Multiple of 3
阅读量:4151 次
发布时间:2019-05-25

本文共 1688 字,大约阅读时间需要 5 分钟。

reference: 

Problem Definition:

The very first solution that comes to our mind is the one that we learned in school.If sum of digits in a number is multiple of 3 then number is multiple of 3 e.g., for 612 sum of digits is 9 so it’s a multiple of 3. But this solution is not efficient. You have to get all decimal digits one by one, add them and then check if sum is multiple of 3.

There is a pattern in binary representation of the number that can be used to find if number is a multiple of 3.If difference between count of odd set bits (Bits set at odd positions) and even set bits is multiple of 3 then is the number.

Solution:

1) Make n positive if n is negative.2) If number is 0 then return 13) If number is 1 then return 04) Initialize: odd_count = 0, even_count = 05) Loop while n != 0    a) If rightmost bit is set then increment odd count.    b) Right-shift n by 1 bit    c) If rightmost bit is set then increment even count.    d) Right-shift n by 1 bit6) return isMutlipleOf3(odd_count - even_count)// do this recursively

Code:

/* Fnction to check if n is a multiple of 3*/int isMultipleOf3(int n){    int odd_count = 0;    int even_count = 0;     /* Make no positive if +n is multiple of 3       then is -n. We are doing this to avoid       stack overflow in recursion*/    if(n < 0)   n = -n;    if(n == 0) return 1;    if(n == 1) return 0;     while(n)    {        /* If odd bit is set then           increment odd counter */        if(n & 1)            odd_count++;        n = n>>1;         /* If even bit is set then           increment even counter */        if(n & 1)            even_count++;        n = n>>1;    }      return isMultipleOf3(abs(odd_count - even_count));}

转载地址:http://dexti.baihongyu.com/

你可能感兴趣的文章
链睿和家乐福合作推出下一代零售业隐私保护技术
查看>>
Unifrax宣布新建SiFAB™生产线
查看>>
艾默生纪念谷轮™在空调和制冷领域的百年创新成就
查看>>
NEXO代币持有者获得20,428,359.89美元股息
查看>>
Piper Sandler为EverArc收购Perimeter Solutions提供咨询服务
查看>>
RMRK筹集600万美元,用于在Polkadot上建立先进的NFT系统标准
查看>>
JavaSE_day14 集合中的Map集合_键值映射关系
查看>>
异常 Java学习Day_15
查看>>
Mysql初始化的命令
查看>>
MySQL关键字的些许问题
查看>>
浅谈HTML
查看>>
css基础
查看>>
Servlet进阶和JSP基础
查看>>
servlet中的cookie和session
查看>>
过滤器及JSP九大隐式对象
查看>>
软件(项目)的分层
查看>>
【Python】学习笔记——-7.0、面向对象编程
查看>>
【Python】学习笔记——-7.2、访问限制
查看>>
【Python】学习笔记——-7.3、继承和多态
查看>>
【Python】学习笔记——-7.5、实例属性和类属性
查看>>