Last digit of Product of two Large or Small numbers (a * b)
Given two large or small numbers, the task is to find the last digit of the product of these two numbers.
Examples:
Input: a = 1234567891233789, b = 567891233156156
Output: 4
Input: a = 123, b = 456
Output: 8
Approach: In general, the last digit of multiplication of 2 numbers a and b is the last digit of the product of the LSB of these two numbers.
For example: For a = 123 and b = 456,
the last digit of a*b
= Last digit of ((LSB of a)*(LSB of b))
= Last digit of ((3)*(6))
= Last digit of (18)
= 8
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void lastDigit(string a, string b)
{
int lastDig = (a[a.length() - 1] - '0' )
* (b[b.length() - 1] - '0' );
cout << lastDig % 10;
}
int main()
{
string a = "1234567891233" , b = "1234567891233156" ;
lastDigit(a, b);
return 0;
}
|
Java
class Solution {
public static void lastDigit(String a, String b)
{
int lastDig = (a.charAt(a.length() - 1 ) - '0' )
* (b.charAt(b.length() - 1 ) - '0' );
System.out.println(lastDig % 10 );
}
public static void main(String[] args)
{
String a = "1234567891233" , b = "1234567891233156" ;
lastDigit(a, b);
}
}
|
Python3
def lastDigit(a, b):
lastDig = (( int (a[ len (a) - 1 ]) - int ( '0' )) *
( int (b[ len (b) - 1 ]) - int ( '0' )))
print (lastDig % 10 )
if __name__ = = '__main__' :
a, b = "1234567891233" , "1234567891233156"
lastDigit(a, b)
|
C#
using System;
class Solution {
public static void lastDigit(String a, String b)
{
int lastDig = (a[a.Length - 1] - '0' )
* (b[b.Length - 1] - '0' );
Console.Write(lastDig % 10);
}
public static void Main()
{
String a = "1234567891233" , b = "1234567891233156" ;
lastDigit(a, b);
}
}
|
PHP
<?php
function lastDigit( $a , $b )
{
$lastDig = (ord( $a [ strlen ( $a ) - 1]) - 48) *
(ord( $b [ strlen ( $b ) - 1]) - 48);
echo $lastDig % 10;
}
$a = "1234567891233" ;
$b = "1234567891233156" ;
lastDigit( $a , $b );
?>
|
Javascript
<script>
function lastDigit(a, b) {
var lastDig = (a[a.length - 1] - '0' )
* (b[b.length - 1] - '0' );
document.write(lastDig % 10);
}
var a = "1234567891233" , b = "1234567891233156" ;
lastDigit(a, b);
</script>
|
Time Complexity: O(1).
Auxiliary Space: O(1)
Last Updated :
22 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...