[英]What is the most efficient way to find the last digit of an int in C++
I want to try writing my own BigInt Class so I am wondering what would be the most efficient way to find the last digit of a number in C, especially for an input that would be an extremely large int.我想尝试编写自己的 BigInt Class,所以我想知道在 C 中找到数字的最后一位数字的最有效方法是什么,特别是对于一个非常大的 int 输入。
lastDigit = number % 10;
I'm assuming that your BigInt uses a base-256 implementation, but this would work equally well for base-65536 or even bigger bases. 我假设您的BigInt使用base-256实现,但这对于base-65536甚至更大的基础也同样有效。
Start with a simple example: BigInt(2828) would be stored as 11*256 + 12. Now BigInt(2828) % 10 = (11*256+12) % 10 = ((11 % 10)*(256 % 10) + 12 % 10)) % 10 = (256 % 10 + 2) % 10 = (6+2) % 10 = 8. 从一个简单的例子开始:BigInt(2828)将存储为11 * 256 + 12.现在BigInt(2828)%10 =(11 * 256 + 12)%10 =((11%10)*(256%10) + 12%10))%10 =(256%10 + 2)%10 =(6 + 2)%10 = 8。
The two basic rules that you'll be applying are (a+b)%10 = (a%10 + b%10) % 10, and (a*b)%10 = (a%10 * b%10) % 10. As it happens, not only is 256 % 10 == 6, but (256^N) % 10 = (6^N) % 10 = 6. This enormously simplifies your LastDigit() function. 您将要应用的两个基本规则是(a + b)%10 =(a%10 + b%10)%10和(a * b)%10 =(a%10 * b%10)% 10.实际上,不仅256%10 == 6,而且(256 ^ N)%10 =(6 ^ N)%10 = 6.这极大地简化了您的LastDigit()函数。
So, again assuming a BigInt B represented as a sequence d_N..d_0 with base 256. Then B % 10 is (6*sum(d_i % 10) - 5 * (d_0 % 10)) % 10. Each term in the summation is at most 9, obviously. 因此,再次假设BigInt B表示为基数为256的序列d_N..d_0。然后B%10为(6 * sum(d_i%10) - 5 *(d_0%10))%10。求和中的每个项显然是最多9个。 Hence you can trivially sum (ULONG_MAX/6) base-256 digits without overflowing, and the same still applies to base-65536 and base-4294967296 因此,您可以简单地求和(ULONG_MAX / 6)base-256位而不会溢出,同样仍然适用于base-65536和base-4294967296
由于您正在处理输入,因此最简单的方法是将其作为字符串读取,并通过减去“0”将最后一个字符转换为数字值。
Try the following:尝试以下操作:
long timestamp = 1661972769123;
long last_3_digits = timestamp - ((timestamp / 1000) * 1000);
Better late than never!迟到总比不到好!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.