Advertisement
VKNikov

findLargestBySumOfDigits

Jul 27th, 2014
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Created by VKNikov on 27.7.2014 г..
  3.  */
  4.  
  5. //Problem 3.    Number with Largest Sum of Digits
  6. //Write a JavaScript function findLargestBySumOfDigits(nums) that takes as an input a sequence of positive integer
  7. // numbers and returns the element with the largest sum of its digits. The function should take a variable number of
  8. // arguments. It should return undefined when 0 arguments are passed or when some of the arguments is not an integer
  9. // number. Write a JS program largestSumOfDigits.js that invokes your function with the sample input data below and
  10. // prints its output at the console.
  11.  
  12. function findLargestBySumOfDigits() {
  13.     "use strict";
  14.  
  15.     var numbers = [];
  16.     var n = arguments.length;
  17.     var sum = 0;
  18.     var tempSum = 0;
  19.     var position = 0;
  20.  
  21.     //This loop push all the arguments in an array (remember, variable number of arguments as input!
  22.     for (var i = 0; i < n; i++) {
  23.         numbers.push(arguments[i]);
  24.     }
  25.     if (numbers == '') {
  26.         console.log('undefined');
  27.         return;
  28.     }
  29.  
  30.     //This loop checks if there is any argument that is not a number.
  31.     for (var i = 0; i < n; i++) {
  32.         var integer = parseFloat(numbers[i]);
  33.         var checkFloating = parseFloat(numbers[i]);
  34.         var roundedNumber = Math.floor(checkFloating);
  35.  
  36.         if (isNaN(integer) || checkFloating !== roundedNumber) {
  37.             console.log('undefined');
  38.             return;
  39.         }
  40.     }
  41.    
  42.     //This loop checks which number has the highest sum of it's digits. Note that as per the task's conditions this
  43.     // function should take only positive integers, but one of the inputs contains a negative integer and that negative
  44.     // integer is the correct answer. Strange, isn't it :).
  45.     for (var i = 0; i < n; i++) {
  46.         var numberAsString = numbers[i].toString().replace(/-/, '');
  47.         var length = numberAsString.length;
  48.         for (var j = 0; j < length; j++) {
  49.             tempSum += parseInt(numberAsString[j]);
  50.         }
  51.  
  52.         if (tempSum > sum) {
  53.             sum = tempSum;
  54.             position = numbers[i];
  55.         }
  56.         tempSum = 0;
  57.     }
  58.  
  59.  
  60.     console.log(position);
  61. }
  62.  
  63. findLargestBySumOfDigits(5, 10, 15, 111);
  64. findLargestBySumOfDigits();
  65. findLargestBySumOfDigits(33, 44, -99, 0, 20);
  66. findLargestBySumOfDigits('hello');
  67. findLargestBySumOfDigits(5, 3.3);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement