Dados tres enteros positivos X , Y y B , donde X e Y son enteros de base B , la tarea es encontrar el valor de X – Y tal que X >= Y .
Ejemplos:
Entrada: X = 1212, Y = 256, B = 8
Salida: 0734
Explicación: El valor de 1212 – 256 en base 8 es 734 .Entrada: X = 546, Y = 248, B = 9
Salida: 287
Enfoque: El problema dado se puede resolver mediante el uso de restas matemáticas básicas. Siga los pasos a continuación para resolver el problema dado:
- Inicialice dos variables, digamos potencia = 1 , acarreo = 0 , para realizar un seguimiento de la potencia actual y el acarreo generado mientras se resta respectivamente.
- Inicialice una variable, digamos finalVal = 0 , para almacenar el valor resultante de X – Y.
- Iterar un ciclo hasta que X > 0 y realizar los siguientes pasos:
- Almacene los últimos dígitos del valor actual de X e Y en dos variables, digamos n1 = X % 10 y n2 = Y % 10 respectivamente.
- Elimine los últimos dígitos de X e Y actualizando X = X / 10 e Y = Y / 10 .
- Inicializar temp = n1 – n2 + carry .
- Si temp < 0 , agregue base B a N , es decir N = N + B y establezca carry = -1 , que actuará como un préstamo. De lo contrario, establezca llevar = 0 .
- Agregue temp * power actual a finalVal, es decir, finalVal = finalVal + temp * power y configure power = power * 10 .
- Después de completar los pasos anteriores, imprima el valor de finalVal como resultado.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find X - Y in base B int getDifference(int B, int X, int Y) { // To store final answer int finalVal = 0; // To store carry generated int carry = 0; // To keep track of power int power = 1; while (X > 0) { // Store last digits of current // value of X and Y in n1 and // n2 respectively int n1 = X % 10; int n2 = Y % 10; // Remove last digits from // X and Y X = X / 10; Y = Y / 10; int temp = n1 - n2 + carry; if (temp < 0) { // Carry = -1 will act // as borrow carry = -1; temp += B; } else { carry = 0; } // Add in final result finalVal += temp * power; power = power * 10; } // Return final result return finalVal; } // Driver Code int main() { int X = 1212; int Y = 256; int B = 8; cout << (getDifference(B, X, Y)); return 0; } // This code is contributed by rakeshsahni
Java
// Java program for the above approach import java.io.*; class GFG { // Function to find X - Y in base B public static int getDifference( int B, int X, int Y) { // To store final answer int finalVal = 0; // To store carry generated int carry = 0; // To keep track of power int power = 1; while (X > 0) { // Store last digits of current // value of X and Y in n1 and // n2 respectively int n1 = X % 10; int n2 = Y % 10; // Remove last digits from // X and Y X = X / 10; Y = Y / 10; int temp = n1 - n2 + carry; if (temp < 0) { // Carry = -1 will act // as borrow carry = -1; temp += B; } else { carry = 0; } // Add in final result finalVal += temp * power; power = power * 10; } // Return final result return finalVal; } // Driver Code public static void main(String[] args) { int X = 1212; int Y = 256; int B = 8; System.out.println( getDifference(B, X, Y)); } }
Python3
# Python3 program for the above approach # Function to find X - Y in base B def getDifference(B, X, Y) : # To store final answer finalVal = 0; # To store carry generated carry = 0; # To keep track of power power = 1; while (X > 0) : # Store last digits of current # value of X and Y in n1 and # n2 respectively n1 = X % 10; n2 = Y % 10; # Remove last digits from # X and Y X = X // 10; Y = Y // 10; temp = n1 - n2 + carry; if (temp < 0) : # Carry = -1 will act # as borrow carry = -1; temp += B; else : carry = 0; # Add in final result finalVal += temp * power; power = power * 10; # Return final result return finalVal; # Driver Code if __name__ == "__main__" : X = 1212; Y = 256; B = 8; print(getDifference(B, X, Y)); # This code is contributed by AnkThon
C#
// C# program for the above approach using System; public class GFG { // Function to find X - Y in base B public static int getDifference(int B, int X, int Y) { // To store final answer int finalVal = 0; // To store carry generated int carry = 0; // To keep track of power int power = 1; while (X > 0) { // Store last digits of current // value of X and Y in n1 and // n2 respectively int n1 = X % 10; int n2 = Y % 10; // Remove last digits from // X and Y X = X / 10; Y = Y / 10; int temp = n1 - n2 + carry; if (temp < 0) { // Carry = -1 will act // as borrow carry = -1; temp += B; } else { carry = 0; } // Add in final result finalVal += temp * power; power = power * 10; } // Return final result return finalVal; } // Driver Code public static void Main(string[] args) { int X = 1212; int Y = 256; int B = 8; Console.WriteLine(getDifference(B, X, Y)); } } // This code is contributed by AnkThon
Javascript
<script> // Javascript program for the above approach // Function to find X - Y in base B function getDifference(B, X, Y) { // To store final answer let finalVal = 0; // To store carry generated let carry = 0; // To keep track of power let power = 1; while (X > 0) { // Store last digits of current // value of X and Y in n1 and // n2 respectively let n1 = X % 10; let n2 = Y % 10; // Remove last digits from // X and Y X = Math.floor(X / 10); Y = Math.floor(Y / 10); let temp = n1 - n2 + carry; if (temp < 0) { // Carry = -1 will act // as borrow carry = -1; temp += B; } else { carry = 0; } // Add in final result finalVal += temp * power; power = power * 10; } // Return final result return finalVal; } // Driver Code let X = 1212; let Y = 256; let B = 8; document.write(getDifference(B, X, Y)); // This code is contributed by gfgking </script>
Producción:
734
Complejidad de tiempo: O(log 10 N)
Espacio auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por atharvakarpe y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA