https://zyrastory.com/wp-includes/js/jquery/jquery.min.js
https://zyrastory.com/wp-includes/js/jquery/jquery-migrate.min.js
(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "btkbh92jgl");
(function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
m[i].l=1*new Date();
for (var j = 0; j < document.scripts.length; j++) {if (document.scripts[j].src === r) { return; }}
k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
(window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");ym(93103491, "init", {
clickmap:true,
trackLinks:true,
accurateTrackBounce:true
});
(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};t=l.createElement(r);t.async=1;
t.src="https://www.clarity.ms/tag/"+i+"?ref=wordpress";y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "btkbh92jgl");
跳至主要內容
文章觀看次數: 686
LeetCode題目翻譯 英文原文如下
Implement pow(x, n) , which calculates x raised to the power n (i.e., xn ).
實作一個 pow函式 , 計算 x 的 n 次方 (換句話說,就是 X n )
這題的題目限制比較沒什麼重要的, n 為Integer (介於Int32的區間)
直接來看下範例吧
第一題根本就是工程師的送分題呢,最熟悉的2的10次方 – 1024 (之後有機會再為了她出一篇文章)
來看下第三題,大家都忘光光的負次方,X的負n次方 ➔ X的n次方之一 ➔ 1/Xn
解題思路 講到次方還有什麼要注意的呢?
那結合以上幾個推論,我們來實作看看
C# 解決方案 ❌首次嘗試 – 直接迴圈
public class Solution {
public double MyPow(double x, int n) {
if(x == 0)
{
return 0.0;
}
else if (n == 0)
{
return 1.0;
}
double res = 1;
bool neg = n < 0; //negative power : 負的次方
if(neg)
{
n*=-1;
}
//多少次方就乘多少次,反正n為整數
for(int i = 0;i<n;i++)
{
res*=x;
}
//負的次方,最後要變回幾分之一
if(neg)
{
res = 1/res;
}
return res;
}
}
看起來沒什麼問題吧? 測試範例應該也都可以過
那我們大膽地按下 Submit 吧 !
超過時間限制了
而且還是在這種笨笨的範例上,1的整數次方一定也是1…
你說寫法有問題嗎?就邏輯上來說還確實沒有呢
這時我們再來想一下該調整邏輯
方案1 – 修正版
我們這時來想一下
2的8次方也就是 2*2*2*2*2*2*2*2
是不是可以寫成 22 * 22 * 22 * 22 也就是 4 的4次方
而4的4次方又可以寫成 42 * 42 也就是 16的平方
要是我們能得到16再來進行計算,是不是就不用跑這麼多次了
public class Solution {
public double MyPow(double x, int n) {
if(x == 0)
{
return 0.0;
}
double res = cal(x, n);
return n>0 ? res : 1/res;
}
private double cal(double x, int n)
{
//Console.WriteLine("x:"+x+",n="+n); //註1
if (n == 0)
{
return 1.0;
}
double res = cal(x*x,n/2) ;
return n%2 == 0 ? res : res*x;
}
}
大家測試時可以將註1 的註解移掉,可以幫助大家理解邏輯
我們一樣拿 x = 2 ,n = 8 來計算 ( 28 )
第五次遞迴因為n為 0,所以會回傳 1
故我們看回第四次遞迴,n為1 1不是2的倍數 (n%2 == 0),故需要res * x ➔ res為第五次遞迴迴傳的1 ➔ 回傳 1*256
其他次因為n均為2的整數,故都直接回傳
所以可以得到 256
Java解 決方案方案1
class Solution {
public double myPow(double x, int n) {
if(x == 0)
{
return 0.0;
}
double res = cal(x, n);
return n>0 ? res : 1/res;
}
private double cal(double x, int n)
{
if (n == 0)
{
return 1.0;
}
double res = cal(x*x,n/2);
return n%2 == 0 ? res : res*x;
}
}
Python3 解決方案方案1
def cal(x: float, n: int) -> float:
if n == 0:
return 1.0
res = cal(x*x,(int)(n/2))
return res if n%2 == 0 else res*x
class Solution:
def myPow(self, x: float, n: int) -> float:
if x == 0:
return 0
res = cal(x, n)
return res if n>0 else 1/res
JavaScript 解決方案方案1
/**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function(x, n) {
if(x == 0)
{
return 0.0;
}
res = cal(x, n);
return n>0 ? res : 1/res;
};
function cal(x, n)
{
if (n == 0)
{
return 1.0;
}
res = cal(x*x,parseInt(n/2));
return n%2 == 0 ? res : res*x;
}
結論 這一題都之前的 LeetCode #507 Perfect Number 一樣,看到就會很直覺寫出一個辦法
但效能都不算優良,提交會得到超時的錯誤
故如何轉念思考及變換邏輯是很重要的
"Knowledge is power."
Francis Bacon 知識就是力量,而在這題,知識不只是力量,更是「power 次方」
圖片來源 : 封面圖片- Photo by Kamran Chaudhry on Unsplash
英文翻譯 – 劍橋詞典
題目連結 : Pow(x, n) – LeetCode
🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸
🧡可以的話,幫我的FaceBook 粉絲專頁按個讚,我會很感謝的
✅如有任何疑問,歡迎透過留言或messenger讓我知道 !
function closePop(){document.getElementById("headlineatas").style.display = 'none';}
function openPop()
{
if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent))
{
return false;
}
var r = Math.random();
if(r>0.7 || r<0.3)
{
document.getElementById("headlineatas").style.display = '';
}
}
(function (d, sc, u) {
var s = d.createElement(sc),
p = d.getElementsByTagName(sc)[0];
s.type = "text/javascript";
s.async = true;
s.src = u;
p.parentNode.insertBefore(s, p);
})(
document,
"script",
"https://affiliate.klook.com/widget/fetch-iframe-init.js"
);
(adsbygoogle = window.adsbygoogle || []).push({});
(function (d, sc, u) {
var s = d.createElement(sc),
p = d.getElementsByTagName(sc)[0];
s.type = "text/javascript";
s.async = true;
s.src = u;
p.parentNode.insertBefore(s, p);
})(
document,
"script",
"https://affiliate.klook.com/widget/fetch-iframe-init.js"
);
(adsbygoogle = window.adsbygoogle || []).push({});
(adsbygoogle = window.adsbygoogle || []).push({});
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
js = d.createElement(s); js.id = id;
js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js#xfbml=1&version=v6.0&autoLogAppEvents=1'
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function returnDefault(item)
{
item.innerText = "Copy"
item.style.color = "white"
item.style.backgroundColor = "CornflowerBlue";
}
if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) == false) //20221128 手機用戶移除copy功能
{
jQuery('code').each(function () {
var btn = document.createElement("button");
btn.innerHTML = "Copy";
btn.onmousedown = "event.preventDefault();";
btn.setAttribute('class', 'btnC');
btn.onclick = function(){
var k = this.nextSibling;
var textArea = document.createElement("textarea");
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;// Clean up any borders.
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';// Avoid flash of the white box if rendered for any reason.
textArea.style.background = 'transparent';textArea.value = k.textContent;document.body.appendChild(textArea);
textArea.focus();
textArea.select();var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';if(successful)
{
this.focus();
this.style.backgroundColor = "green";
this.innerText = "✔Copied"
//openPop();
setTimeout(( ()=>returnDefault(this)),1850)
}document.body.removeChild(textArea);
};var parent = this.parentNode;
parent.insertBefore(btn, this);
});
}
var eztoc_smooth_local = {"scroll_offset":"30","add_request_uri":""};
https://zyrastory.com/wp-content/plugins/easy-table-of-contents/assets/js/smooth_scroll.min.js
https://zyrastory.com/wp-content/plugins/easy-table-of-contents/vendor/js-cookie/js.cookie.min.js
https://zyrastory.com/wp-content/plugins/easy-table-of-contents/vendor/sticky-kit/jquery.sticky-kit.min.js
var ezTOC = {"smooth_scroll":"1","visibility_hide_by_default":"","scroll_offset":"30","fallbackIcon":"<span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span>","chamomile_theme_is_on":""};
https://zyrastory.com/wp-content/plugins/easy-table-of-contents/assets/js/front.min.js
https://zyrastory.com/wp-content/plugins/highlighting-code-block/assets/js/prism.js
var hcbVars = {"showCopyBtn":"","copyBtnLabel":"Copy code to clipboard"};
https://zyrastory.com/wp-content/plugins/highlighting-code-block/build/js/hcb_script.js
var ct_localizations = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","public_url":"https:\/\/zyrastory.com\/wp-content\/themes\/blocksy\/static\/bundle\/","rest_url":"https:\/\/zyrastory.com\/wp-json\/","search_url":"https:\/\/zyrastory.com\/search\/QUERY_STRING\/","show_more_text":"\u986f\u793a\u66f4\u591a","more_text":"\u66f4\u591a","search_live_results":"\u641c\u5c0b\u7d50\u679c","search_live_no_result":"\u627e\u4e0d\u5230\u7b26\u5408\u7684","search_live_one_result":"\u60a8\u5df1\u627e\u5230 %s \u500b\u7b26\u5408\u7684. \u8acb\u6309 Tab \u9375\u4f86\u9078\u64c7\u5b83.","search_live_many_results":"\u60a8\u5df1\u627e\u5230 %s \u500b\u7b26\u5408\u7684. \u8acb\u6309 Tab \u9375\u4f86\u9078\u64c7\u5b83.","expand_submenu":"\u5c55\u958b\u4e0b\u62c9\u9078\u55ae","collapse_submenu":"\u6536\u5408\u4e0b\u62c9\u9078\u55ae","dynamic_js_chunks":[],"dynamic_styles":{"lazy_load":"https:\/\/zyrastory.com\/wp-content\/themes\/blocksy\/static\/bundle\/non-critical-styles.min.css?ver=2.0.45","search_lazy":"https:\/\/zyrastory.com\/wp-content\/themes\/blocksy\/static\/bundle\/non-critical-search-styles.min.css?ver=2.0.45","back_to_top":"https:\/\/zyrastory.com\/wp-content\/themes\/blocksy\/static\/bundle\/back-to-top.min.css?ver=2.0.45"},"dynamic_styles_selectors":[{"selector":".ct-header-cart, #woo-cart-panel","url":"https:\/\/zyrastory.com\/wp-content\/themes\/blocksy\/static\/bundle\/cart-header-element-lazy.min.css?ver=2.0.45"},{"selector":".flexy","url":"https:\/\/zyrastory.com\/wp-content\/themes\/blocksy\/static\/bundle\/flexy.min.css?ver=2.0.45"}],"lang":"zh"};
https://zyrastory.com/wp-content/themes/blocksy/static/bundle/main.js
https://zyrastory.com/wp-includes/js/comment-reply.min.js
(function() {
var expirationDate = new Date();
expirationDate.setTime( expirationDate.getTime() + 31536000 * 1000 );
document.cookie = "pll_language=zh; expires=" + expirationDate.toUTCString() + "; path=/; secure; SameSite=Lax";
}());
window.addEventListener("DOMContentLoaded",(e=>{document.querySelectorAll('img[loading="lazy"]').forEach((e=>{e.getBoundingClientRect().top<=window.innerHeight&&(e.loading="eager")}))}));
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};