在Java中用0和1替換負數和正數矩陣元素
在Java中,陣列是一個物件。它是一種非基本資料型別,用於儲存相同資料型別的值。Java中的矩陣只不過是一個多維陣列,表示多行和多列。
這裡我們給出了一個包含一組元素的矩陣,這些元素包括正數和負數,根據問題陳述,我們必須用0替換負數,用1替換正數。
讓我們深入研究本文,瞭解如何使用Java程式語言來實現這一點。
為您展示一些例項
例項-1
給定矩陣 =
-21 22 -23 24 -25 26 -27 -28 29
替換負數為0,正數為1後,
結果矩陣為 -
0 1 0 1 0 1 0 0 1
例項-2
給定矩陣 =
-9 2 -2 4 -1 -7 -2 6 2 -2 -4 3 -1 4 7 -8
替換負數為0,正數為1後,
結果矩陣為 -
0 1 0 1 0 0 0 1 1 0 0 1 0 1 1 0
例項-3
給定矩陣 =
-1 -2 -3 4 5 6 -7 8 -9
替換負數為0,正數為1後,
結果矩陣為:-
0 0 0 1 1 1 0 1 0
演算法
演算法-1
步驟-1 - 建立一個二維陣列矩陣來儲存數字。
步驟-2 - 呼叫replaceNum方法,用0替換矩陣中的負數,用1替換正數。
步驟-3 - 列印結果矩陣。
步驟-4 - 在replaceNum方法中,使用for迴圈遍歷矩陣的行和列。
步驟-5 - 對於矩陣中的每個元素,使用三元運算子根據它是負數還是正數將其替換為0或1。
演算法-2
步驟-1 - 建立一個二維陣列矩陣來儲存數字。
步驟-2 - 呼叫replaceNum方法,用0替換矩陣中的負數,用1替換正數。
步驟-3 - 列印結果矩陣。
步驟-4 - 在replaceNum方法中,使用for迴圈遍歷矩陣的行和列。
步驟-5 - 對於矩陣中的每個元素,使用Math.signum方法確定數字的符號(負數為-1,0為0,正數為1)。然後使用if-else語句根據它是負數還是正數將其替換為0或1
語法
要獲取陣列的長度(陣列中元素的數量),陣列有一個內建屬性,即length
下面是它的語法 -
array.length
其中,“array”指的是陣列引用。
Java中的Math.signum()方法是一個數學函式,它返回給定double或float值的符號(負數為-1,0為0,正數為1)。
下面是它的語法 -
Math.signum(mat[a][b]) == -1.0)
其中,“mat”指的是給定的矩陣。
多種方法
我們提供了不同方法的解決方案。
使用三元運算子
使用Math.signum函式
讓我們逐一檢視程式及其輸出。
方法-1:使用三元運算子
在這種方法中,矩陣元素將在程式中初始化。然後透過將矩陣作為引數傳遞來呼叫使用者定義的方法,並在方法內部根據演算法使用三元運算子將負數替換為0,將正數替換為1。
示例
public class Main {
public static void main(String[] args) {
int[][] inputMatrix = {{-1, 2, -3},
{4, -5, 6},
{7, 8, -9}};
// Call the User-defined method to replace negative and positive numbers
replacenum(inputMatrix);
// Print the resultant matrix
for (int a = 0; a < inputMatrix.length; a++) {
for (int b = 0; b < inputMatrix[a].length; b++) {
System.out.print(inputMatrix[a][b] + " ");
}
System.out.println();
}
}
// User-defined method to replace numbers
public static void replacenum(int[][] mat) {
for (int a = 0; a < mat.length; a++) {
for (int b = 0; b < mat[a].length; b++) {
// Use a ternary operator to replace the number
mat[a][b] = mat[a][b] < 0 ? 0 : 1;
}
}
}
}
輸出
0 1 0 1 0 1 1 1 0
方法-2:使用Math.signum函式
在這種方法中,矩陣元素將在程式中初始化。然後透過將矩陣作為引數傳遞來呼叫使用者定義的方法,並在方法內部根據演算法使用Math.signum方法將負數替換為0,將正數替換為1。
示例
public class Main {
public static void main(String[] args) {
int[][] inputMatrix = {{-1, -2, 3},
{4, -5, -6},
{7, 8, 9}};
// Call the User-defined method to replace negative and positive numbers
replaceNum(inputMatrix);
// Print the resultant matrix
for (int a = 0; a < inputMatrix.length; a++) {
for (int b = 0; b < inputMatrix[a].length; b++) {
System.out.print(inputMatrix[a][b] + " ");
}
System.out.println();
}
}
// User-defined method to replace numbers
public static void replaceNum(int[][] mat) {
for (int a = 0; a < mat.length; a++) {
for (int b = 0; b < mat[a].length; b++) {
// Use an if-else statement with Math.signum method to replace the number
if (Math.signum(mat[a][b]) == -1.0) {
mat[a][b] = 0;
} else {
mat[a][b] = 1;
}
}
}
}
}
輸出
0 0 1 1 0 0 1 1 1
在本文中,我們探討了使用Java程式語言在矩陣中用0替換負數,用1替換正數的不同方法。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP