Giải Thuật Căn Bản Trong Javascript – Nghịch đảo Chuỗi Và Tính Giai ...

Hôm nay ta sẽ đi tìm hiểu về 2 bài toán cơ bản thường thấy trong giải thuật đó là: Nghịch đảo chuỗi và tính giai thừa

Nghịch đảo chuỗi

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Show hidden characters
function reverseString(str) {
return str.split('').reverse().join('');
}

view raw Reverse.js hosted with ❤ by GitHub

Bài toán về giai thừa

Trước tiên là ta dùng vòng lặp for … loop để giải quyết bài toán. Trong đó ta chú ý đến điều kiện, số cần tính cần lớn hơn 1

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Show hidden characters
function factorialize(num) {
for (a=1; num>=1; num–) {
a = a*num;
}
return a;
}
factorialize(5);

view raw Factorialize.js hosted with ❤ by GitHub

Hoặc ta có thể dùng đệ quy như sau:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Show hidden characters
function factorialize(num) {
if (num === 0) { return 1; }
return num * factorialize(num-1);
}
factorialize(5);

view raw Factorialize.js hosted with ❤ by GitHub

Share this:

  • X
  • Facebook
Like Loading...

Related

Từ khóa » Tính Giai Thừa Trong Javascript