[英]Why isn't my code returning the “maximum” number of consecutive 1's for the specific input “524275”?
我正在嘗試解決HackerRank Day of Code 10 。
簡而言之,任務是在十進制數的二進制表示形式中找到最大的連續1個數。 在我的代碼中,我嘗試使用兩個變量: count
和hold
。 每當字符串的當前位置和上一個位置均為1時, count
增加1。只要第i個位置為0, count
的值就會分配給變量hold
。 在以下迭代中,如果count
的值超過hold
的值,則將count
的值分配為hold
。 這樣,最大連續1個數被保存在hold
。 最后,我打印了hold
的值。
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter decimal number");
int n = in.nextInt();
String binary = Integer.toString(n,2);
int count=1;
int hold=0;
if(binary.equals("0"))
System.out.println(0);
else
{
for(int i=0;i<binary.length();i++)
{
if(i==0){}
else if(binary.charAt(i-1)=='1' && binary.charAt(i)=='1')
{
count++;
}
if(count>hold)
hold=count;
if(binary.charAt(i)=='0')
{
hold=count;
count=1;
}
}
System.out.println(hold);
}
}
}
我的代碼不適用於示例輸入“ 524275”,該輸入以二進制格式轉換為“ 1111111111111110011”。 輸出結果是2,這很奇怪。 編寫我的代碼,以便返回連續1的“最大”數。 我哪里做錯了? 我嘗試過干斷代碼,但是還無法發現錯誤。
在使用for循環處理了前15
個后, hold
實際上將具有值15
。 然后,您遇到第一個零,並且if(binary.charAt(i)=='0') { hold=count; count=1; }
if(binary.charAt(i)=='0') { hold=count; count=1; }
if(binary.charAt(i)=='0') { hold=count; count=1; }
將count
重置為1
。 但是隨后您立即找到另一個零,並且代碼相同if(binary.charAt(i)=='0') { hold=count; count=1; }
if(binary.charAt(i)=='0') { hold=count; count=1; }
if(binary.charAt(i)=='0') { hold=count; count=1; }
將1
hold
,您將丟失信息15
。
一個簡單的解決方案是刪除該行hold=count;
在這一行。 您已經在上方設置了hold
三行。 (正確的是,因為只有在count
大於之前的最佳值時才執行此操作。
該方法非常復雜。 如果您想要一種更簡單的方法。 該代碼應該是不言自明的。
int current_consecutive_ones = 0;
int best_consecutive_ones = 0;
for(int i = 0; i < binary.length(); i++)
{
if (binary.charAt(i) == '1')
current_consecutive_ones++;
else
current_consecutive_ones = 0;
if (current_consecutive_ones > best_consecutive_ones)
best_consecutive_ones = current_consecutive_ones;
}
System.out.println(best_consecutive_ones);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.