📜  TCS编码实践问题|倒数

📅  最后修改于: 2021-05-28 03:15:28             🧑  作者: Mango

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

例子:

Input: num = 12345
Output: 54321

Input: num = 786
Output: 687

方法:

  • 由于该数字是作为命令行参数输入的,因此不需要专用的输入行
  • 从命令行参数中提取输入数字
  • 提取的数字将为String类型。
  • 将此数字转换为整数类型并将其存储在变量中,例如num
  • 初始化一个变量,例如rev_num,将这个数字的倒数存储为0
  • 现在遍历数字num直到它变为0,即(num> 0)
  • 在每次迭代中
    • 将rev_num乘以10,然后将num的余数相加。这会将num的最后一位存储在rev_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基础课程》。