Функция реверса и добавления

Опубликовано: 20 Января, 2022

Функции реверса и сложения начинаются с числа, меняют его цифры на обратные и добавляют обратное к оригиналу. Если сумма не является палиндромом, повторяйте эту процедуру до тех пор, пока она не станет точной.

Напишите программу, которая берет число и дает результирующий палиндром (если он существует). Если потребовалось более 1000 итераций (добавлений) или получился палиндром, превышающий 4 294 967 295, предположим, что для данного числа палиндром не существует.

Примеры:

Сырьё: 195
Выход: 9339

Ввод: 265
Выход: 45254

Ввод: 196
Вывод: палиндрома не существует.  

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

C++

// C++ Program to implement reverse and add function
#include<bits/stdc++.h>
using namespace std;
  
/* Iterative function to reverse digits of num*/
long long reversDigits(long long num)
{
    long long rev_num = 0;
    while (num > 0)
    {
        rev_num = rev_num*10 + num%10;
        num = num/10;
    }
    return rev_num;
}
  
/* Function to check whether he number is palindrome or not */
bool isPalindrome(long long num)
{
    return (reversDigits(num) == num);
}
  
/* Reverse and Add Function */
void ReverseandAdd(long long num)
{
    long long rev_num=0;
    while (num <= 4294967295)
    {
        // Reversing the digits of the number
        rev_num = reversDigits(num);
  
        // Adding the reversed number with the original
        num = num + rev_num;
  
        // Checking whether the number is palindrome or not
        if (isPalindrome(num))
        {
            printf("%lld ",num);
            break;
        }
        else if (num > 4294967295)
        {
            printf("No palindrome exist");
        }
    }
}
  
// Driver Program
int main()
{
    ReverseandAdd(195);
    ReverseandAdd(265);
    return 0;
}

Java

// Java Program to implement reverse and add function
public class ReverseAdd 
{
    /* Iterative function to reverse digits of num*/
    long reversDigits(long num)
    {
        long rev_num = 0;
        while (num > 0)
        {
            rev_num = rev_num*10 + num%10;
            num = num/10;
        }
        return rev_num;
    }
  
    /* Function to check whether he number is
           palindrome or not */
    boolean isPalindrome(long num)
    {
        return (reversDigits(num) == num);
    }
  
    /* Reverse and Add Function */
    void ReverseandAdd(long num)
    {
        long rev_num = 0;
        while (num <= 4294967295l)
        {
            // Reversing the digits of the number
            rev_num = reversDigits(num);
  
            // Adding the reversed number with the original
            num = num + rev_num;
  
            // Checking whether the number is palindrome or not
            if(isPalindrome(num))
            {
                System.out.println(num);
                break;
            }
            else if (num > 4294967295l)
            {
                System.out.println("No palindrome exist");
            }
        }
    }
      
    // Main method
    public static void main(String[] args) 
    {
        ReverseAdd ob = new ReverseAdd();
        ob.ReverseandAdd(195l);
        ob.ReverseandAdd(265l);
          
    }
}

Python

#Python Program to implement reverse and add function
  
# Iterative function to reverse digits of num
def reversDigits(num):
    rev_num=0
    while (num > 0):
        rev_num = rev_num*10 + num%10
        num = num/10
    return rev_num
  
# Function to check whether the number is palindrome or not
def isPalindrome(num):
    return (reversDigits(num) == num)
  
# Reverse and Add Function
def ReverseandAdd(num):
    rev_num = 0
    while (num <= 4294967295):
        # Reversing the digits of the number
        rev_num = reversDigits(num)
  
        # Adding the reversed number with the original
        num = num + rev_num
  
        # Checking whether the number is palindrome or not
        if(isPalindrome(num)):
            print num
            break
        else:
            if (num > 4294967295):
                print "No palindrome exist"
  
# Driver Code
ReverseandAdd(195)
ReverseandAdd(265)

C#

// C# Program to implement reverse and add function
using System;
  
class GFG 
{
    /* Iterative function to reverse digits of num*/
    static long reversDigits(long num)
    {
        long rev_num = 0;
        while (num > 0)
        {
            rev_num = rev_num * 10 + num % 10;
            num = num / 10;
        }
        return rev_num;
    }
  
    /* Function to check whether he number is
        palindrome or not */
    static bool isPalindrome(long num)
    {
        return (reversDigits(num) == num);
    }
  
    /* Reverse and Add Function */
    static void ReverseandAdd(long num)
    {
        long rev_num = 0;
        while (num <= 4294967295)
        {
            // Reversing the digits of the number
            rev_num = reversDigits(num);
  
            // Adding the reversed number with the original
            num = num + rev_num;
  
            // Checking whether the number is palindrome or not
            if(isPalindrome(num))
            {
                Console.WriteLine(num);
                break;
            }
            else if (num > 4294967295)
            {
                Console.WriteLine("No palindrome exist");
            }
        }
    }
      
    // Driver code
    public static void Main() 
    {
        ReverseandAdd(195);
        ReverseandAdd(265);
    }
}
  
// This code is contributed by chandan_jnu

PHP

<?php
// PHP Program to implement reverse and add function
  
/* Iterative function to reverse digits of num*/
function reversDigits($num)
{
    $rev_num = 0;
    while ($num > 0)
    {
        $rev_num = $rev_num * 10 + $num % 10;
        $num = (int)($num / 10);
    }
    return $rev_num;
}
  
/* Function to check whether he number
   is palindrome or not */
function isPalindrome($num)
{
    return (reversDigits($num) == $num);
}
  
/* Reverse and Add Function */
function ReverseandAdd($num)
{
     $rev_num = 0;
    while ($num <= 4294967295)
    {
        // Reversing the digits of the number
        $rev_num = reversDigits($num);
  
        // Adding the reversed number with
        // the original
        $num = $num + $rev_num;
  
        // Checking whether the number is
        // palindrome or not
        if (isPalindrome($num))
        {
            print($num . " ");
            break;
        }
        else if ($num > 4294967295)
        {
            print("No palindrome exist");
        }
    }
}
  
// Driver Code
ReverseandAdd(195);
ReverseandAdd(265);
  
// This code is contributed by chandan_jnu
?>


Output:

9339
45254

Ссылки : https://app.assembla.com/spaces/AASU_Fall2008_ProgrammingTeam/wiki

Эта статья предоставлена Рахулом Агравалом . Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью на сайте deposit.geeksforgeeks.org или отправить свою статью по электронной почте: grant@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.

Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.

Вниманию читателя! Не прекращайте учиться сейчас. Получите все важные математические концепции для соревновательного программирования с курсом Essential Maths for CP по доступной для студентов цене. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

РЕКОМЕНДУЕМЫЕ СТАТЬИ