在对codebyte进行挑战时,我找到了其他人的解决方案。但是,他的代码不适用于其中一个测试用例,但我不明白为什么。
挑战信息:输入是2个字符串的数组,第一个字符串包含2个数字,分别表示秤的两边的权重。第二个字符串包含您可以用来尝试平衡秤的权重。目标:用最少的重量(最多2个)平衡秤并输出您使用的重量。
代码输出1,6,它可以实现秤的平衡,但是秤也可以仅由一个砝码平衡。5.为什么第一个“返回”键不会脱离该功能?
function ScaleBalancing(strArr) {
const w1 = JSON.parse(strArr[0])[0];
const w2 = JSON.parse(strArr[0])[1];
let weights = JSON.parse(strArr[1]);
for (let i = 0; i < weights.length; i++) {
if (w1 + weights[i] === w2 || w2 + weights[i] === w1) {
return '' + weights[i]; // should return 5 and break out of function right?
}
//if this for loop is omitted the function returns 5
for (let j = i + 1; j < weights.length; j++) {
if (w1 + weights[i] + weights[j] === w2 ||
w2 + weights[i] + weights[j] === w1 ||
w1 + weights[i] === w2 + weights[j] ||
w2 + weights[i] === w1 + weights[j]) {
return '' + weights[i] + ',' + weights[j]; //this returns 1,6
}
}
}
return 'not possible';
}
// keep this function call here
ScaleBalancing(["[6, 1]", "[1, 10, 6, 5]"]);
答案 0 :(得分:0)
的原因是外循环从//above 22
if (Build.VERSION.SDK_INT > 22) {
//for dual sim mobile
SubscriptionManager localSubscriptionManager = SubscriptionManager.from(this);
if (localSubscriptionManager.getActiveSubscriptionInfoCount() > 1) {
//if there are two sims in dual sim mobile
List localList = localSubscriptionManager.getActiveSubscriptionInfoList();
SubscriptionInfo simInfo = (SubscriptionInfo) localList.get(0);
SubscriptionInfo simInfo1 = (SubscriptionInfo) localList.get(1);
final String sim1 = simInfo.getDisplayName().toString();
final String sim2 = simInfo1.getDisplayName().toString();
}else{
//if there is 1 sim in dual sim mobile
TelephonyManager tManager = (TelephonyManager) getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String sim1 = tManager.getNetworkOperatorName();
}
}else{
//below android version 22
TelephonyManager tManager = (TelephonyManager) getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String sim1 = tManager.getNetworkOperatorName();
}
索引开始。在这一点上,代码不知道0
会在数组中的某个时候出现。
对于第一个数字5
,条件1
为(w1 + weights[i] === w2 || w2 + weights[i] === w1)
,因此它进入嵌套的false
循环。
如果将for
放在5
之前,代码将返回1
5