📜  TCS 编码练习题 |一个数的总和

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

给定一个数字,任务是使用命令行参数找到这个数字的数字总和。

例子:

Input: num = 687
Output: 21

Input: num = 12
Output: 3

方法:

  • 由于数字是作为命令行参数输入的,因此不需要专用的输入行
  • 从命令行参数中提取输入数字
  • 这个提取的数字将是字符串类型。
  • 将此数字转换为整数类型并将其存储在变量中,例如 num
  • 声明一个变量来存储总和并将其设置为 0
  • 重复接下来的两步,直到数字不为0
  • 借助余数 ‘%’运算符获得最右边的数字,方法是将其除以 10 并将其添加到总和中。
  • 借助“/”运算符将数字除以 10
  • 打印或返回总和

程序:

C
// C program to find
// the sum of digits of a number
// using command line arguments
  
#include 
#include  /* atoi */
  
// Function to Find the sum of digits
int findSumOfDigits(int num)
{
  
    // Variable to store the
    // the sum of digits
    int sum = 0;
  
    // Traverse through the number digit by digit
    while (num > 0) {
  
        // Add the last digit of num
        // to the sum
        sum = sum + (num % 10);
  
        // Remove the last digit from the num
        num = num / 10;
    }
  
    // Return the sum
    return sum;
}
  
// 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]);
  
        // Find the sum of digits and print it
        printf("%d\n", findSumOfDigits(num));
    }
    return 0;
}


Java
// Java program to find
// the sum of digits of a number
// using command line arguments
  
class GFG {
  
    // Function to Find the sum of digits
    public static int findSumOfDigits(int num)
    {
  
        // Variable to store the
        // the sum of digits
        int sum = 0;
  
        // Traverse through the number digit by digit
        while (num > 0) {
  
            // Add the last digit of num
            // to the sum
            sum = sum + (num % 10);
  
            // Remove the last digit from the num
            num = num / 10;
        }
  
        // Return the sum
        return sum;
    }
  
    // 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 n = Integer.parseInt(args[0]);
  
            // Find the sum of digits and print it
            System.out.println(findSumOfDigits(n));
        }
        else
            System.out.println("No command line "
                               + "arguments found.");
    }
}


输出:

  • 在 C 中:
  • 在Java:
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解语言和 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程