Logic to check the number is divisible by 3 or not?

后端 未结 10 1466
清歌不尽
清歌不尽 2021-01-14 16:31

without using %, / or * , I have to find the no. is divisible by 3 or not?

it might be an interview question.

Thanks.

10条回答
  •  执笔经年
    2021-01-14 16:47

    Here is a reasonably efficient algorithm for large numbers. (Well not very efficient, but reasonable given the constraints.)

    Use sprintf to convert it to a string, convert each digit back to a number. Add up the digits. If you come up with 3, 6, or 9, it is divisible by 3. Anything else less than 10, it is not. Anything over 9, recurse.

    For instance to test the number 813478902 you'd stringify, then add the digits to get 42, add those digits to get 6, so it is divisible by 3.

提交回复
热议问题