[英]Why this programe getting an error that is taking too much time to execute error
public static int meth(int N)
{
int count1=0;
int count2=0;
int tot=0;
while(N>=1)
{
if(N%2==0)
{
N=N/2;//2
count1++;//1
//i=0;
}
else if(N%2!=0)
{
N=(N+1)/2;
count2++;
//i=0;
}
else if(N==1)
{
count2++;
N=0;
}
}
tot=count1+count2;
return tot;
}
public static void main(String[] args) {
int i=meth(4);
System.out.println(i);
}
如果 N 能被 2 整除,則 N/2 種食物 如果 N 不能被 2 整除,則 (N+1)/2 種食物。
示例 1: 輸入:N=4 Output: 3 解釋:在第一秒,一個人將吃掉 (4/2) 件食物,之后剩下的食物將是 2。在第二秒,該人將吃掉 (2/2) 件食物,所以食物item left 將為 1.In 2nd second he will eat (((1+1)/2) item so food item left will be 0. Example 2: Input: N=0 Output: 0 Explanation: There is no food items to eat .
就像我在評論中所說的那樣,您的代碼會導致無限循環。 解決方案就是簡單地切換你的第二個和第三個,如果這樣的話。 這樣 N 將有機會達到 0 並結束循環。
public static int meth(int N){
int count1=0;
int count2=0;
int tot=0;
while(N>=1){
if(N%2==0){
N=N/2;//2
count1++;//1
//i=0;
}else if(N==1){
count2++;
N=0;
}else if(N%2!=0){
N=(N+1)/2;
count2++;
//i=0;
}
}
tot=count1+count2;
return tot;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.