我在做一些練習時遇到了一個非常熟悉的問題,并且在我的一生中無法使用預期的方法(模數%運算子)來解決它,該方法接受(int min, int max)引數作為開始和結束限制。
它是通過呼叫列印以下內容numberSquare(1, 5):
12345
23451
34512
45123
51234
我已經通過創建手動跟蹤器來實作它,盡管我知道這不是正確的方法:
private static void numberSquare(int min, int max)
{
int difference = max - min;
// outside loop
for(int row = min; row <= max; row )
{
// inside loop
for(int col = row; col <= row difference; col )
{
// is in bounds
if(col <= max)
System.out.print(col);
// not in bounds
else
System.out.print(col - difference - 1);
} // next line
System.out.println();
}
}
我使用運算子的另一種方法的內部回圈如下所示:
// is in bounds
if(col <= max)
System.out.print(col);
// not in bounds
else
System.out.print(col % max min);
這給了我一個輸出:
|12345| |12345|
|23452| |23451|
|34523| instead of |34512|
|45234| |45123|
|52345| |51234|
我真的很想看看如何使用模數%運算子來做到這一點,并且希望得到任何幫助/建議。
編輯以獲取更多資訊
我有另一個版本可以作業,但是這個也沒有%操作員......
private static void numberSquare(int min, int max)
{
// track outside rows
for(int row = min ; row <= max; row )
{
// track inside columns and the print value
for(int col = min, value = row;
col <= max; col , value )
{
// reset if the value is too high
value = (value > max) ? min : value;
System.out.print(value);
}
// next line
System.out.println();
}
}
uj5u.com熱心網友回復:
假設您的整數是abcd每個字母都是數字的地方。您可以通過首先分離bcd和a
bcd = abcd % 1000
a = abcd / 1000 (integer division)
然后,從bcd和構造左回圈移位a
bcda = bcd * 10 a
在Java中,這就是我將如何實作它
void numSquare(int min, int max) {
int number = 0;
int div = 1;
// construct the integer, e.g., 12345, and the corresponding power of tens
for (int i = max; i >= min; --i) {
number = i * div;
div *= 10;
}
div /= 10;
// left cyclic shifting the integer and printing
int nShifts = max - min 1;
for (int i = 0; i < nShifts; i) {
System.out.println(number);
number = (number % div) * 10 (number / div);
}
}
如果您想逐位列印并且必須使用%,訣竅是減去列min以將范圍移動到[0, max-min],%一旦達到最大值就使用 重復,然后重新添加min以將其恢復到正常范圍,就像這樣
void numSquare(int min, int max) {
int len = max - min 1;
for (int row = min; row <= max; row ) {
for (int col = row; col < row len; col ) {
System.out.print((col - min) % len min);
}
System.out.println(); // break line when we do a new row
}
}
如果可能的話,我會建議不要使用這種方法,因為它對 的呼叫很多System.out.print,隨著時間的推移會累積起來。
uj5u.com熱心網友回復:
您可以將值計算為(row col - 2) % max 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477846.html
上一篇:根據索引組合串列
