a = 0.1、b = 0.100001 (2 進数で -- つまり、10 進数で a = 0.5、b = 0.515625) のような入力では失敗します。この場合、正解は 0.1 になりますが、アルゴリズムは代わりに 0.11 を生成します。これは、最小長であるだけでなく、b よりも大きくなります :-(
あなたの数字チェックは私にはうまく見えます-問題は、ループを終了する(正しい)決定をしたときに、bの数字文字列が長い場合、間違った出力を作成することです。これを修正する簡単な方法の 1 つは、数字を一度に 1 つずつ出力することです。別の文字が表示されるまで、現在の文字を含める必要があることがわかります。
もう 1 つのヒント: 私は Javascript をよく知りませんが、どちらのparseInt()
呼び出しも不要だと思います。u
v
[編集]
以下は、いくつかの考慮事項を組み込んだ 1 桁ずつのコードの例です。
var binaryInInterval = function(a, b) {
if (a < 0 || b > 1 || a >= b) return undefined;
if (a == 0) return '0'; // Special: only number that can end with a 0
var i, j, u, v, x = '';
a = a.toString(2).replace('.', '');
b = b.toString(2).replace('.', '');
for (i = 0; i < Math.min(a.length, b.length); i++) {
u = a.substr(i, 1);
v = b.substr(i, 1);
if (u != v) {
// We know that u must be '0' and v must be '1'.
// We therefore also know that u must have at least 1 more '1' digit,
// since you cannot have a '0' as the last digit.
if (i < b.length - 1) {
// b has more digits, meaning it must
// have more '1' digits, meaning it must be larger than
// x if we add a '1' here, so it's safe to do that and stop.
x += '1'; // This is >= a, because we know u = '0'.
} else {
// To ensure x is >= a, we need to look for the first
// '0' in a from this point on, change it to a '1',
// and stop. If a only contains '1's from here on out,
// it suffices to copy them, and not bother appending a '1'.
x += '0';
for (j = i + 1; j < a.length; ++j) {
if (a.substr(j, 1) == '0') {
break;
}
}
}
break; // We're done. Fall through to fix the binary point.
} else {
x += u; // Business as usual.
}
}
// If we make it to here, it must be because either (1) we hit a
// different digit, in which case we have prepared an x that is correct
// except for the binary point, or (2) a and b agree on all
// their leftmost min(len(a), len(b)) digits. For (2), it must therefore be
// that b has more digits (and thus more '1' digits), because if a
// had more it would necessarily be larger than b, which is impossible.
// In this case, x will simply be a.
// So in both cases (1) and (2), all we need to do is fix the binary point.
if (x.length > 1) x = '0.' + x.substr(1);
return x;
};