我在极客中接受了一次对极客的采访,在那里我遇到了一个魔术火柴棒问题,我没能及时解决。一天后,我自己解决了这个问题,在堆栈溢出的情况下,我也没能找到解决方案,所以如果您遇到这个问题,这里有一个解决方案:
//magic match-stick problem
/*in this problem set we are given n number of match boxes,
* you need to add matches in a match that is
* the n number of matches in each box,
* but the catch is instead of adding the matches,
* you need to subtract the matches pair that you will be inserting in place
* of every new match stick until there is only last box left with final match stick score
* eg: 1st match box: 4match sticks: 1,2,3,4 match numbers
* 2nd time: 2 match sticks : (1-2), (3-4)=> 1, 1
* last time: (1-1) => 0
*
* I know I cannot explain the problem correctly in English, but I will be able to explain it to you in hindi v well
* also if you can understand the code, you will understand the question
* this took me one day to solve, many minor mistakes I did
* this is a geeks for geeks interview question
* question name magical matchsticks*/
public class practice{
public static void main(String args[]) {
int a[] = {1,2,3,4,5,6};
int num;
int count;
int n = a.length;
do
{
num=0;
count=0;
if(n==1)
{
System.out.println(a[0]+"last");
}
else if(n>1)
{
if(n%2==0)
{
n=n/2;
for(int i = 0; i<((n)) ; i++)
{
a[i] = a[num]-a[num+1];
if(a[i]<0)
{
a[i] = a[i]*(-1);
System.out.print(a[i]+" "+a[i + 1]);
}
System.out.println(" a ");
num = num + 2;
count++;
}
}
else if(n%2==1)
{
n = (n/2) +1;
for(int i = 0; i<(n); i++)
{
a[i] = a[num]-a[num+1];
if(a[i]<0)
{
a[i] = a[i]*(-1);
System.out.print(a[i]+" "+a[i + 1]);
}
System.out.println("b ");
num = num + 2;
count++;
}
}
}
System.out.println(n);
for(int j = 0; j<a.length;j++)
{
System.out.print(a[j]);
}
System.out.println(" ");
}while(n>1);
for(int k = 0; k<a.length;k++)
{
System.out.print(a[k]);
}
System.out.println(" ");
}
}这个问题将显示程序进行过程中的所有步骤,您将需要进行更改,以便从一个单独的类或函数返回值。
我将开始为这个帐户上的竞争性编程提供解决方案。
发布于 2022-10-09 07:59:12
这个问题是用上面的答案来解决的。
在我的github页面上也提供了答案:
https://stackoverflow.com/questions/74003023
复制相似问题