java - 加法竞争编程
问题描述
问题是:
最近,Chef 研究了二进制数字系统,并注意到对非负整数执行 AND、XOR 或位移等按位运算非常简单,而执行算术运算(例如加法、乘法或除法)则要复杂得多.
在玩了一段时间的二元运算之后,Chef 发明了一个有趣的算法,用于将两个非负整数 A 和 B 相加:
function add(A, B):
while B is greater than 0:
U = A XOR B
V = A AND B
A = U
B = V * 2
return A
现在 Chef 想知道这个算法有多快。给定 A 和 B 的初始值(二进制表示),他需要你帮助他计算算法的 while 循环重复的次数。
输入 :
- 输入的第一行包含一个整数 T,表示测试用例的数量。T 测试用例的描述如下。
- 每个测试用例的第一行包含一个字符串 A。
- 第二行包含一个字符串 B。
输出: 对于每个测试用例,打印包含一个整数的单行——算法在给定数字 A 和 B 相加期间将执行的迭代次数。
约束: * 1≤T≤105 * 1≤|A|,|B|≤105 * A 和 B 仅包含字符 '0' 和 '1' * |A|+|B| 之和 在所有测试用例中不超过 106
示例案例: A和B的初始值分别为111002=28和10102=10。第一次迭代后,它们的值分别变为 22 和 16。在第二次迭代后,它们变为 6 和 32,最后在第三次迭代后变为 38 和 0。
我试过解决这个问题,我的解决方案是:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc = new Scanner(System.in);
int testCases = 0;
if(sc.hasNext())
{
//Take no.of test cases
testCases = sc.nextInt();
}
//Count of While Loop
int iterationCount = 0;
while(testCases!=0)
{
//A and B Variables
long A = Integer.parseInt(sc.next(), 2);
long B = Integer.parseInt(sc.next(),2);
long U,V;
//While Loop To Get Addition
while(B > 0)
{
U =Math.abs(A) ^ Math.abs(B);
V = Math.abs(A) & Math.abs(B);
A = U;
B = V * 2;
iterationCount++;
}
//Print the Count
System.out.println(iterationCount);
iterationCount = 0;
}
testCases--;
}
}
它在 VSCode IDE 上运行良好,但是当我尝试在 CODECHEF 上运行它时,出现运行时错误!运行时错误 (NZEC)。
我的代码有什么问题?
解决方案
NZEC 代表非零退出代码,在您的情况下,这是因为您的 while 循环不会终止,这导致程序永远不会终止,并且您不能在 Codechef 平台上拥有非终止程序。
您应该testCases
在 while 循环内部而不是外部递减。应该是这样的:
while (testCases != 0) {
//
// Your code
//
testCases--;
}
推荐阅读
- amazon-web-services - awsvpc:网络配置对于此任务定义的给定 networkMode 无效
- html - 用html填充输入字段时隐藏css中的文本不起作用
- python - How to generate timstamp for a day?
- flutter - 如何快速复制和增加数量?
- angular - 如何在 Angular 7 中同时执行多个 API 请求
- sql - oracle中的空行填充
- python - 使用 hvplot 在散点图中悬停时显示额外的列
- css - 带有 nth-child 的 CSS 选择器考虑像组这样的元素列表
- deep-learning - 哪种 GAN 模型最适合使用配对数据集生成 beard 和 no_beard 图像
- visual-studio - 仅在项目已更改时创建 Nuget 包