📜  TCS 编码练习题 |反转数字

📅  最后修改于: 2021-10-23 07:35:00             🧑  作者: Mango

给定一个数字,任务是使用命令行参数反转这个数字。

例子:

Input: num = 12345
Output: 54321

Input: num = 786
Output: 687

方法:

  • 由于数字是作为命令行参数输入的,因此不需要专用的输入行
  • 从命令行参数中提取输入数字
  • 这个提取的数字将是字符串类型。
  • 将此数字转换为整数类型并将其存储在变量中,例如 num
  • 初始化一个变量,比如 rev_num,用 0 存储这个数字的倒数
  • 现在循环遍历数字 num 直到它变成 0,即 (num > 0)
  • 在每次迭代中,
    • 将 rev_num 乘以 10 并加上 num 的余数。这将在 rev_num 中存储 num 的最后一位数字
    • 将 num 除以 10 以从中删除最后一位数字。
  • 循环结束后,rev_num 与 num 相反。

程序:

C
// C program to reverse a number
// using command line arguments
  
#include 
#include      /* atoi */
  
// Function to reverse the number
int reverseNumber(int num)
{
  
    // Variable to store the
    // resultant reverse number
    int rev_num = 0;
  
    // Traverse through the number digit by digit
    while (num > 0) {
  
        // Append the last digit of num
        // as the next digit of rev_num
        rev_num = rev_num * 10 + num % 10;
  
        // Remove the last digit from the num
        num = num / 10;
    }
  
    // Return the reversed number
    return rev_num;
}
  
// Driver code
int main(int argc, char* argv[])
{
  
    int num;
  
    // Check if the length of args array is 1
    if (argc == 1)
        printf("No command line arguments found.\n");
    else {
  
        // Get the command line argument and
        // Convert it from string type to integer type
        // using function "atoi( argument)"
        num = atoi(argv[1]);
  
        // Reverse the number and print it
        printf("%d\n", reverseNumber(num));
    }
    return 0;
}


Java
// Java program to reverse a number
// using command line arguments
  
class GFG {
  
    // Function to reverse the number
    public static int reverseNumber(int num)
    {
  
        // Variable to store the
        // resultant reverse number
        int rev_num = 0;
  
        // Traverse through the number digit by digit
        while (num > 0) {
  
            // Append the last digit of num
            // as the next digit of rev_num
            rev_num = rev_num * 10 + num % 10;
  
            // Remove the last digit from the num
            num = num / 10;
        }
  
        // Return the reversed number
        return rev_num;
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Check if length of args array is
        // greater than 0
        if (args.length > 0) {
  
            // Get the command line argument and
            // Convert it from string type to integer type
            int num = Integer.parseInt(args[0]);
  
            // Reverse the number and print it
            System.out.println(reverseNumber(num));
        }
        else
            System.out.println("No command line "
                               + "arguments found.");
    }
}


输出:

  • 在 C 中:
  • 在Java:

想要从精选的视频和练习题中学习,请查看C 基础到高级C 基础课程