当前位置:网站首页>试除法--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;
}
};边栏推荐
- Representation and implementation of stack (C language)
- 关于拼多多根据关键词取商品列表 API 的使用说明
- 拼多多根据ID取商品详情 API 的使用说明
- Stm32- analyze latency based on assembly
- Compile live555 with vs2019 in win10
- 牛市还没有结束,还有下半场 2021-05-18
- NVIDIA programmable reasoning accelerator tensorrt learning notes (III) -- Accelerating reasoning
- 京东获取推荐商品列表 API
- Nest.js 用了 Express 但也没完全用
- MySQL - database log
猜你喜欢
![Niuke / Luogu - [noip2003 popularization group] stack](/img/95/871b1c6f492b467bffd25912304b44.gif)
Niuke / Luogu - [noip2003 popularization group] stack

网站服务器停止响应是什么意思?

YoloV4-tiny网络结构

OPENCV学习DAY6

Security document archiving software

After using MQ message oriented middleware, I began to regret

Binary tree - 530. Minimum absolute difference of binary search tree

Module II operation

"Animal coin" is fierce, trap or opportunity? 2021-05-12

Recent impressions about bull market and defi 2021-05-17
随机推荐
Unified handling of global exceptions
BGR and RGB convert each other
Cherish time and improve efficiency
栈的表示和实现(C语言)
Prometheus operation and maintenance tool promtool (II) query function
OPENCV学习DAY6
关于“DBDnet: A Deep Boosting Strategy for ImageDenoising“一文理解
Stack and queue - 239. Sliding window maximum
Pinduoduo gets the usage instructions of the product details API according to the ID
计算物理期刊修改
痞子衡嵌入式:MCUXpresso IDE下将源码制作成Lib库方法及其与IAR,MDK差异
Appium中控件元素封装类梳理
Solid smart contract development - 3.2-solid syntax array, structure, mapping
06_ue4进阶_使用地形工具设置大地图
Iterator pattern of behavioral pattern
Backtracking - 77. combination
redis的使用
获得JD商品详情原数据 API
Jd.com API for obtaining recommended product list
Leetcode high frequency question 66. add one, give you an array to represent numbers, then add one to return the result