Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by VKNikov on 27.7.2014 г..
- */
- //Problem 3. Number with Largest Sum of Digits
- //Write a JavaScript function findLargestBySumOfDigits(nums) that takes as an input a sequence of positive integer
- // numbers and returns the element with the largest sum of its digits. The function should take a variable number of
- // arguments. It should return undefined when 0 arguments are passed or when some of the arguments is not an integer
- // number. Write a JS program largestSumOfDigits.js that invokes your function with the sample input data below and
- // prints its output at the console.
- function findLargestBySumOfDigits() {
- "use strict";
- var numbers = [];
- var n = arguments.length;
- var sum = 0;
- var tempSum = 0;
- var position = 0;
- //This loop push all the arguments in an array (remember, variable number of arguments as input!
- for (var i = 0; i < n; i++) {
- numbers.push(arguments[i]);
- }
- if (numbers == '') {
- console.log('undefined');
- return;
- }
- //This loop checks if there is any argument that is not a number.
- for (var i = 0; i < n; i++) {
- var integer = parseFloat(numbers[i]);
- var checkFloating = parseFloat(numbers[i]);
- var roundedNumber = Math.floor(checkFloating);
- if (isNaN(integer) || checkFloating !== roundedNumber) {
- console.log('undefined');
- return;
- }
- }
- //This loop checks which number has the highest sum of it's digits. Note that as per the task's conditions this
- // function should take only positive integers, but one of the inputs contains a negative integer and that negative
- // integer is the correct answer. Strange, isn't it :).
- for (var i = 0; i < n; i++) {
- var numberAsString = numbers[i].toString().replace(/-/, '');
- var length = numberAsString.length;
- for (var j = 0; j < length; j++) {
- tempSum += parseInt(numberAsString[j]);
- }
- if (tempSum > sum) {
- sum = tempSum;
- position = numbers[i];
- }
- tempSum = 0;
- }
- console.log(position);
- }
- findLargestBySumOfDigits(5, 10, 15, 111);
- findLargestBySumOfDigits();
- findLargestBySumOfDigits(33, 44, -99, 0, 20);
- findLargestBySumOfDigits('hello');
- findLargestBySumOfDigits(5, 3.3);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement