当前位置:网站首页>试除法--3的幂
试除法--3的幂
2022-07-26 00:09:00 【獜洛橙】
问题描述:
给定一个整数,写一个函数来判断它是否是 3 的幂次方。如果是,返回 true ;否则,返回 false 。
整数 n 是 3 的幂次方需满足:存在整数 x 使得 n == 3^x
示例 1:
输入:n = 27
输出:true
示例 2:输入:n = 0
输出:false
示例 3:输入:n = 9
输出:true
示例 4:输入:n = 45
输出:false来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/power-of-three
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
问题分析:
从问题分析可知,要判断是3的幂的数,也就是不可能是负数和零,肯定是正数,那么用不断地用n模除3判断是否等于0的方法,就可以判断出n是否是3的幂,而最终的条件就是,如果该数是3的幂,最后肯定结果是1%3==0不成立,从而退出循环,而此时n==1,那么只要返回n==1,问题就迎刃而解。
代码如下:
class Solution {
public:
bool isPowerOfThree(int n) {
while(n && n%3==0)
n/=3;
return n==1;
}
};边栏推荐
- URL address mapping configuration
- Backtracking - 17. Letter combinations of phone numbers
- Binary tree - 226. Flip binary tree
- Observer model of behavioral model
- FreeRTOS个人笔记-互斥量
- 用了MQ消息中间件后,我开始后悔了...
- Representation and implementation of stack (C language)
- NVIDIA可编程推理加速器TensorRT学习笔记(三)——加速推理
- Yes, UDP protocol can also be used to request DNS server
- Elementary C language - branch statements (if, switch)
猜你喜欢

IP核:PLL

NVIDIA可编程推理加速器TensorRT学习笔记(三)——加速推理

Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK

Solve the problem of rapid index bar extrusion

Binary tree -- 222. Number of nodes of a complete binary tree

Module II operation

LeetCode高频题66. 加一,给你一个数组表示数字,则加1返回结果

Recent impressions about bull market and defi 2021-05-17

07_ UE4 advanced_ MP value of firing fireball and mechanism of attacking blood deduction

关于“DBDnet: A Deep Boosting Strategy for ImageDenoising“一文理解
随机推荐
Stack and queue - 239. Sliding window maximum
获得JD商品详情原数据 API
How to make your JS code more beautiful
Under inflation, how to operate in the future? 2021-05-14
Module II operation
MySQL——主从复制
[one library] mapbox GL! A map engine out of the box
Stm32- analyze latency based on assembly
06_ue4进阶_使用地形工具设置大地图
Leetcode169 detailed explanation of most elements
栈的表示和实现(C语言)
This time, thoroughly understand promise principle
合肥提前批
The bull market will continue. Take your money 2021-05-08
Leetcode shahutong series -- 63. Different paths II
[英雄星球七月集训LeetCode解题日报] 第25日 树状数组
Linked list related methods
STM32 lighting procedure
MPLS中的包交换和标签交换
LeetCode 沙胡同系列 -- 63. 不同路径 II