如何将一个数除3而不使用*、/、+、-、%等运算符?
号码可以有签名,也可以没有签名。
如何将一个数除3而不使用*、/、+、-、%等运算符?
号码可以有签名,也可以没有签名。
当前回答
3以2为底等于11。
所以只要做长除法(就像中学那样),以2 × 11为底。以2为底比以10为底更简单。
对于从最有效位开始的每个位位:
判断prefix是否小于11。
如果它是输出0。
如果不是输出1,则替换前缀位进行适当的更改。只有三种情况:
11xxx -> xxx (ie 3 - 3 = 0)
100xxx -> 1xxx (ie 4 - 3 = 1)
101xxx -> 10xxx (ie 5 - 3 = 2)
所有其他前缀都不可达。
重复到最低位,你就完成了。
其他回答
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int num = 1234567;
int den = 3;
div_t r = div(num,den); // div() is a standard C function.
printf("%d\n", r.quot);
return 0;
}
通过使用eval和字符串连接来在“幕后”使用/操作符是欺骗吗?
例如,在Javacript中,您可以这样做
function div3 (n) {
var div = String.fromCharCode(47);
return eval([n, div, 3].join(""));
}
使用Linux shell脚本:
#include <stdio.h>
int main()
{
int number = 30;
char command[25];
snprintf(command, 25, "echo $((%d %c 3)) ", number, 47);
system( command );
return 0;
}
请看我的另一个答案。
使用itoa转换为以3为基数的字符串。去掉最后一个小调,转换回10进制。
// Note: itoa is non-standard but actual implementations
// don't seem to handle negative when base != 10.
int div3(int i) {
char str[42];
sprintf(str, "%d", INT_MIN); // Put minus sign at str[0]
if (i>0) // Remove sign if positive
str[0] = ' ';
itoa(abs(i), &str[1], 3); // Put ternary absolute value starting at str[1]
str[strlen(&str[1])] = '\0'; // Drop last digit
return strtol(str, NULL, 3); // Read back result
}
在PHP中使用BC数学:
<?php
$a = 12345;
$b = bcdiv($a, 3);
?>
MySQL(来自Oracle的采访)
> SELECT 12345 DIV 3;
帕斯卡:
a:= 12345;
b:= a div 3;
X86-64汇编语言:
mov r8, 3
xor rdx, rdx
mov rax, 12345
idiv r8