6/17/2014
1:54:00 PM 0

Variable-length Argument in Java, C#, Python

  • Java
    public int sum(int... nums) 
    {
        //nums.getClass().getTypeName() -> int[]
        int total = 0;
        for (int num : nums ) 
            total += num;
        return total;
    }
    
  • C#
    public int Sum(params int[] nums) 
    {
        //nums.GetType() -> System.Int32[]
        int total = 0;
        for (int i = 0; i < nums.Length; i++)
            total += nums[i];
        return total;
    }
    
  • Python
  • def sum(*nums):
        #type(nums) -> <class 'tuple'>
        total = 0
        for num in nums:
            total += num
        return total
    

0 comments:

Post a Comment