326. Is the square root of 3 ispowerofthree

Source: Internet
Author: User
Tags square root

Own version
  
 
  1. public static bool IsPowerOfThree(int n) {
  2. if (n == 1) {
  3. return true;
  4. }
  5. double num = n;
  6. bool isPower = false;
  7. while (num >= 1) {
  8. num = num / 3;
  9. if (num == 1 && num == (int)num) {
  10. return true;
  11. }
  12. }
  13. return isPower;
  14. }


Recursive version
  
 
  1. public static bool IsPowerOfThree(int n) {
  2. if (n == 1) {
  3. return true;
  4. } else if (n == 0 || n % 3 > 0) {
  5. return false;
  6. } else {
  7. return IsPowerOfThree(n / 3);
  8. }
  9. }

Finally, there is a clever way to make use of the logarithm of the change of the formula to do, the high school has learned the bottom formula for log AB = LogCB/logCA, then if N is a multiple of 3, then log3n must be an integer, we can write it as log by using the change formula3n = Log10N/log103, note here must use 10 as the base, can not use the natural number or 2 as the base, otherwise when the n=243 error, the reason please seeThis post. Now the question becomes a judgment log.10N/log103 is an integer, in C + + to determine whether the number A is an integer, we can use A-int (a) = = zero to determine, see the code is as follows:

           
          
  1. class Solution {
  2. public:
  3. bool isPowerOfThree(int n) {
  4. return (N> 0 && int(log10(N) /log10(3)) -log10(N) /log10(3) == 0);
  5. }
  6. };



From for notes (Wiz)

326. Is the square root of 3 ispowerofthree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.