重複單數字的平方
問題“重複單數字的平方”讓我們做什麼?讓我們來解讀一下!
問題“重複單數字的平方”旨在找到像 33、44、555 等包含重複單數字的數字的平方。
方法 1:樸素方法
我們可以使用樸素方法來計算數字的平方,這包括以下步驟:
將數字作為輸入
使用乘法運算子計算平方,即 square_of_number = number * number
然後列印結果
C++ 實現
以下是上述方法的實現
示例
#include <iostream>
using namespace std;
int main() {
int num = 333;
// input the number
long long res = num * num; // calculate the square
cout << "The square of " <<num<< " is =" <<res << endl; // output the result
return 0;
}
輸出
The square of 333 is =110889
時間複雜度:O(1)
空間複雜度:O(1)
方法 2:寫成 1111…1 的倍數
每個這樣的數字都可以表示為 1111…1 的倍數。例如,33333 = 3 * 11111。
11、111、1111、11111……的平方分別為 121、12321、1234321、123454321 等。
對於計算 11,111,… 的平方,我們有一個模式。檢視此連結。
因此,一個簡單的解決方案是找到 111…11 的平方,然後將結果乘以 3、4、5、6 等(取決於重複的數字)。
我們可以使用大數乘法來獲得最終結果。
程式碼實現
示例
#include <iostream>
#include <cmath>
using namespace std;
long long square_of_ones(int num) {
int n = log10(num) + 1;
long long square = 0;
for (int i = 1; i <= n; i++) {
square= square* 10 + i;
}
for (int i = n - 1; i >= 1; i--) {
square= square* 10 + i;
}
return square;
}
int main() {
int num = 44;
long long res = square_of_ones(num); // calculate the square
int last_digit = num % 10;
cout << "The square of " <<num<< " is =" <<res * last_digit * last_digit<< endl; // output the result
return 0;
}
輸出
The square of 44 is =1936
時間複雜度:O(n)
空間複雜度:O(1)
結論
在本文中,我們嘗試使用兩種不同的方法解釋計算具有重複單數字的數字的平方的步驟。我希望這篇文章能幫助你更好地理解計算背後的概念。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP