LeetCode算法题-Power Of Three(Java实现-七种解法)

用python将dycom .dcm格式图像转换为nifti .nii 因为发现目前搜索到的多数中文教程并不能正确将FMRI图像正确转换,例如很多用simpleITk的seriesreader的,所以写了一下自己正确转换的方法。因为FMRI是一个4D数据,有时间轴,所以用seriesreader读写出来的图像把时间轴维度给降维了。当然你用SPM12工具的dycom import也是能正确转换的,但是我还是喜欢python这样的,代码直接简单。 阅读详情

这是悦乐书的第204次更新,第215篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第71题(顺位题号是326)。给定一个整数,写一个函数来确定它是否为3的幂。例如:

输入:27
输出:true

输入:0
输出:false

输入:9
输出:true

输入:45
输出:false

跟进:你可以不使用任何循环/递归吗?

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

新建一个变量,只要其小于n,依次乘上3,最后比较两数是否相等。当然,你也可以做除法。

public boolean isPowerOfThree(int n) {
    long m = 1;
    while (m < n) {
        m *= 3;
    }
    return  m == n;
}

03 第二种解法

使用递归的方法。当n等于0的时候,返回false,当n等于1的时候,返回true。当n大于1的时候,先判断其对3取余是否等于 0,如果等于0,则将n除以3再调用自己。最后返回false。

public boolean isPowerOfThree2(int n) {
    if (n == 0) {
        return false;
    }
    if (n == 1) {
        return true;
    }
    if (n > 1) {
        return n%3 == 0 && isPowerOfThree2(n/3);
    }
    return false;
}

04 第三种解法

将第二种解法的递归换成迭代的方式也可以。

public boolean isPowerOfThree3(int n) {
    if (n == 0) {
        return false;
    }
    if (n == 1) {
        return true;
    }
    while (n%3 == 0) {
        n /= 3;
    }
    return n == 1;
}

05 第四种解法

利用取余。一般的思路是对3取余,但是这只能判断n是否是3的倍数,而不能保证是3的幂次方。但是我们可以反过来对n取余,借助1162261467这个整数,因为它是3的19次方,是int类型范围内3能够取到的最大幂次方数。只要n是3的幂次方,1162261467对n取余都会返回0。

public boolean isPowerOfThree4(int n) {
    return n > 0 && 1162261467%n == 0;
}

06 第五种解法

利用数学中的对数算法。以下是推理步骤:

3^X == N

log (3^X) == log N

X log 3 == log N

X == (log N) / (log 3)

如果n是3的幂次方,那么将两数取对数后再做除法,得到的是一个以幂次方为整数位,以0位小数位的double类型数,那么对其取整再和自身做减法,那么它的绝对值肯定是无限接近于0的。

public boolean isPowerOfThree5(int n) {
    double lg = Math.log(n)/Math.log(3);
    return Math.abs(lg-Math.round(lg)) <= 0.00000000000001;
}

07 第六种解法

借助包装类Integer的toString方法。

Integer.toString(int par1, int par2),par1表示要转成字符串的数字,par2表示要转成的进制表示。我们可以将n转成3进制的数,那么只要是3的幂次方,转换成3进制字符串后,就是一个以1开头尾随k个0的字符串。

public boolean isPowerOfThree6(int n) {
    if (n <= 1) {
        return n == 1;
    }
    return Integer.toString(n, 3).matches("10*");
}

08 第七种解法

将int类型范围内所有3的幂次方整数放入一个HashSet中,然后判断n是否在HashSet中。

public boolean isPowerOfThree7(int n) {
    HashSet<Integer> set = new HashSet<>(Arrays.asList(1, 3, 9, 27, 
            81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441,
            1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467));
    return set.contains(n);
}

09 小结

算法专题目前已连续日更超过两个月,算法题文章71+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

MATLAB应用实战系列(七十七)-基于长时间序列栅格数据的MK检验 1 MK检验介绍 MK检验是曼-肯德尔法,又称Mann—Kenddall 检验法,是一种气候诊断与预测技术,应用Mann-Kendall检验法可以判断气候序列中是否存在气候突变,如果存在,可确定出突变发生的时间。Mann-Kendall检验法也经常用于气候变化影响下的降水、干旱频次趋势检测。目前常用于长时间序列的栅格数据的显著性检验,在植被覆盖度,NDVI,NPP等方面尤为常见。 该检验功能强大,不需要样本遵从一定的分布,部分数据缺失不会对结果造成影响,不受少数异常值的干扰,适用性强。不但可以检验时 阅读详情

相关推荐

别再折腾Windows了!Ubuntu 22.04下USRP X310 + RFNoC + Vivado 2021.1开发环境保姆级搭建指南

本文提供Ubuntu 22.04下USRP X310 + RFNoC + Vivado 2021.1开发环境的详细搭建指南,涵盖系统优化、UHD驱动编译、Vivado配置及硬件验证等关键步骤,帮助射频工程师高效构建稳定的开发环境,显著提升FPGA开发效率。

weixin_29168675的博客 263

leetcode-java-326. Power of Three

/* Given an integer, write a function to determine if it is a power of three. 1.递归 2.数学方法 x = log(n)/log(3),x是整数就可以了 --那么判断整数方法:double类型,则绝对值差小于10e-15;floor类型,则绝对值差小于10e-6 */ public class Solution {

王欢的博客 357

清华数据结构列车调度AC100分

两种思路(1)将目标栈的数据和待混洗的数据逐个进行比较#pragma warning(disable:4996) #include&lt;stdio.h&gt; #include&lt;string.h&gt; #define maxn 1600005 using namespace std; char a[2*maxn][5];//记录操作命令 int stack[maxn]; char pop...

hgtjcxy的博客 927

【Leetcode】:326. Power of Three 问题 in JAVA

Given an integer, write a function to determine if it is a power of three. Follow up: Could you do it without using any loop / recursion? 题目要求不能使用循环或者递归,这里需要用到数学的一点小技巧。 首先如果n《=0,那么一定返货false 如

SKYQQCLOUD的专栏 1289

MS2107 CVBS转USB2.0 音视频采集芯片,支持1080P@30HZ输出

MS2107 是一款视频和音频采集芯片,支持CVBS转USB2.0 ;可以将 CVBS、S-Video 和音频信号通过 USB接口传送到 PC、智能手机和平板电脑上预览或采集。

TEL18967112838的博客 2081

海康视觉平台VisionMaster实战入门:从通讯配置到工具应用

本文为海康VisionMaster视觉平台实战入门指南,详细介绍了从软件安装准备、与PLC等外部设备的通讯配置,到匹配定位、测量、畸变矫正等核心工具的应用方法。通过实战案例拆解,帮助工程师快速掌握如何搭建完整的机器视觉检测与引导定位系统,实现工业自动化项目落地。

weixin_29224309的博客 1035

Leetcode:326. Power of Three(JAVA)

【题目描述】 Given an integer, write a function to determine if it is a power of three. Follow up: Could you do it without using any loop / recursion? 【思路】 不用循环和递归,则: 3^x=n log(3^x) = log

莫名的程序猿 1542

ABAP RANGES及比较符号

RANGES *选项介绍: *1.SIGN 值为 I 和 E 。 I是包含, E是排除, 一般使用I。 2.OPTION 如果HIGH 为空 ,为单值选择 。有 EQ、NE、GT、LE、LT等逻辑操作 对于的 CP包含 NP是排除 如果HIGH 不为空 为区间选择 有BT,NB可选 *3.LOW 低值 *4.HIGH 高值 lt:less than 小于 le:less than or equal to 小于等于 eq:equal to 等于 ne:

Pegasus666的博客 5398

Power of Three

题目描述: Given an integer, write a function to determine if it is a power of three. Follow up: Could you do it without using any loop / recursion? 看一个数是不是3的次幂 这个题递归法就不写了。 由于这题3的次幂本来就不多,直接枚举都行: p

小武思密达的专栏 630

4、高级认证解决方案:Active Directory、LDAP、RADIUS和TACACS+深度解析

本文深入解析了多种高级认证解决方案,包括Active Directory、标准LDAP、RADIUS和TACACS+,涵盖其技术优势、配置步骤及适用场景。同时介绍了如何实现通用用户管理,包括使用第三方认证解决方案和ADSI自助用户管理。通过实际案例部署,展示了如何高效、安全地管理大规模用户认证与权限控制,为企业安全架构提供参考。

o4p5q6r7s的博客 309

基于Simulink的加速度计振动分析:单自由度质量-弹簧-阻尼系统

摘要:基于Simulink的加速度计单自由度振动分析 本文研究了加速度计的单自由度(SDOF)质量-弹簧-阻尼系统模型,通过MATLAB/Simulink平台建立了完整的振动分析仿真系统。文章详细阐述了理论建模过程,推导了系统运动微分方程和传递函数,并提供了Simulink模型搭建的具体步骤和MATLAB实现代码。研究通过正弦扫频、随机振动和冲击响应三种典型输入信号,分析了系统的幅频特性、相频特性及时域响应,验证了加速度计的工作机理。仿真结果表明,该方法能有效模拟加速度计在不同激励条件下的动态特性,为传感器

AI的内部世界的博客 167

power of three java_LeetCode算法题-Power Of Three(Java实现-七种解法)

这是悦乐书的第204次更新,第215篇原创01 看题和准备今天介绍的是LeetCode算法题中Easy级别的第71题(顺位题号是326)。给定一个整数,写一个函数来确定它是否为3的幂。例如:输入:27输出:true输入:0输出:false输入:9输出:true输入:45输出:false跟进:你可以不使用任何循环/递归吗?本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win...

weixin_33413018的博客 133

标准论文参考文献添加方法——Zotero入门使用教程

第一篇论文投出去了,写一下最后一步的参考文献修饰润色吧! 论文的参考文献,即References,是论文的最后一步,相信不管是写毕设论文还是期刊论文都遇到过需要修改参考文献的情况,非常之麻烦。而且参考文献中经常会与生僻奇怪气体出现,一个一个修改非常浪费时间,这里介绍一下一个非常好用的软件Zetero。 第一步:软件的下载安装及绑定Word 尽量使用客户端吧,

MISAYAONE的博客 20万+

java算法题解法_LeetCode算法题-Power Of Three(Java实现-七种解法)

这是悦乐书的第204次更新,第215篇原创 01 看题和准备今天介绍的是LeetCode算法题中Easy级别的第71题(顺位题号是326)。给定一个整数,写一个函数来确定它是否为3的幂。例如:输入:27 输出:true输入:0 输出:false输入:9 输出:true输入:45 输出:false跟进:你可以不使用任何循环/递归吗?本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环...

weixin_34274163的博客 144

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

LeetCode-326. Power of Three [C++][Java]

Given an integern, returntrueif it is a power of three. Otherwise, returnfalse. An integernis a power of three, if there exists an integerxsuch thatn == 3x.

贫道绝缘子的博客 1088

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

leetcode解题之231# Power of Two&326. Power of Three Java版 (判断是否为2,或者3 的幂)

leetcode解题之231# Power of Two Java版 (判断是否为2的幂) 326. Power of Three

mine_song的博客 396

power of three java_LeetCode - Easy - 326. Power of Three

LeetCode - Easy - 326. Power of ThreeTopicMathDescriptionGiven an integer n, return true if it is a power of three. Otherwise, return false.An integer n is a power of three, if there exists an integer...

weixin_28684757的博客 186

leetcode Power of Three

leetcode Power of Three 题目:https://leetcode.com/problems/power-of-three/ 解题思路:不断除以3如果等于1,是3的幂次方,如果不是,不是3的幂次方。 public boolean isPowerOfThree(int n) { if(n==0){ return false; } while(n%3==0)...

厚积薄发的博客 327

(Java)leetcode-326 Power of Three

题目 判断是否为3的幂 Given an integer, write a function to determine if it is a power of three. Example 1: Input: 27 Output: true Example 2: Input: 0 Output: false Example 3: Input: 9 Output: true Example 4...

不思量 242

LeetCode 326. Power of Three 解题报告

LeetCode 326. Power of Three 解题报告

骆小坑的填坑之旅 767

LeetCode-326. Power of Three

Description Follow Up Solution 1(C++) class Solution { public: bool isPowerOfThree(int n) { if(n&lt;3) return n==1? true: false; else return 3*(n/3) == n? isPowerOfThr...

zy2317878的博客 362

leetcode - 326. Power of Three

leetcode - 326

sinat_41679123的博客 538

leetcode- Number of 1 bits, power of two, power of three

leetcode- Number of 1 bits, power of two, power of three

aaasy的博客 394

LeetCode - Easy - 326. Power of Three

Topic Math Description https://leetcode.com/problems/power-of-three/ Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x. Example 1: Input: n

KISS 234

LeetCode笔记:326. Power of Three

判断一个整数是否是3的次方数

Minecraft 1837
上一篇: LeetCode算法题-Range Sum Query Immutable(Java实现)
下一篇: LeetCode算法题-Power of Four(Java实现-六种解法)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址